点击运行,修改成功
修改成功
运行结果
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Shusheng Shi on 2017/5/3.
*/
@RestController
public class HelloController {
@Value("${cupSize}")
/*属性定义在外部属性文件(application.yml),使用占位符将其插入到bean中,Spring装配中,占位符形式为使用${...}包装的属性名称,
若又依赖于组件扫描和自动装配来创建和初始化应用组件,就使用@Value,使用方法与@Autowired非常相似
此时属性文件中cupSize的值就被注入到下面ccupSize变量中了*/
private String cupSize;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
return cupSize;
}
}
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Shusheng Shi on 2017/5/3.
*/
@RestController
public class HelloController {
@Value("${content}")
private String content;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
return content;
}
}
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created by Shusheng Shi on 2017/5/3.
*/
@Component
/*表明该类作为组件类,并告知Spring要为此类创建bean,无需再显示配置该bean,Spring会做好一切*/
@ConfigurationProperties(prefix = "girl")
/*prefix:用来选择哪个属性的前缀名字来绑定
此示例为将girl前缀下的属性映射进来*/
//当配置文件属性较多时,将配置文件属性写到一个类中,需要属性值可以随意,而不需使用@Value一个一个累到死地注入
public class GirlProperties {
private String cupSize;
private Integer age;
public String getCupSize() {
return cupSize;
}
public void setCupSize(String cupSize) {
this.cupSize = cupSize;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
相应的控制器类改为
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Shusheng Shi on 2017/5/3.
*/
@RestController
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String say() {
return girlProperties.getCupSize();
}
}
运行结果