1.注入普通字符串
@Value("My name is Shelly")
private String name;
2.注入操作系统属性
@Value("#{systemProperties['os.name']}")
private String osName;
3.注入表达式结果
@Value("#{T(java.lang.Math).random() * 100.0}")
private String randomNumber;
4.注入其他Bean属性
@Value("#{testService.another}")
private String fromAnother;
5.注入文件资源
@Value("classpath:com/moam/config/text.txt")
private String testFile;
6.注入网址资源
@Value("http:www.baidu.com")
private String testUrl;
7.注入配置文件
@Value("${index.name}")
private String indexName;
注入配置文件需使用@PropertySource
指定properties文件位置,且使用的是$而不是#,具体如何配置和使用可参考https://blog.csdn.net/weixin_45609759/article/details/117226276
然而当我们的配置有许多个时,我们就需要用@Value注入很多次,这样显得格外麻烦。
SpringBoot提供了基于类型安全的配置方式,@ConfigurationProperties
将properties属性和一个Bean及其属性关联。
①配置application.properties
user.name=xxx
user.age=22
②Bean代码
@Component
// 指定配置文件位置
@PropertySource("classpath:application.properties")
// prefix指定properties的配置的前缀
@ConfigurationProperties(prefix = "user")
public class TestBean {
private String name;
private Long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
检验代码:
@RestController
public class TestApplication{
@Autowired
private TestBean testBean;
@RequestMapping("/")
public String index(){
return "user name is " + testBean.getName() + "user age is " + testBean.getAge();
}
}