版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012869196/article/details/83106217
属性配置
@Value与@ConfigurationProperties比较
功能 | @ConfigurationProperties | @Value |
---|---|---|
注入方式 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验(@Validated) | 支持 | 不支持 |
复杂类型封装 | 支持 | 不 |
应用场景
无论配置文件yml还是properties,它们都能获取到值
若只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value
若专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties
applicaton.yml
person:
lastName: [email protected]
age: 30
birth: 2018/05/06
maps: {k1: v1,k2: v2}
lists:
- test1
- test2
dog:
name: 小秃子
age: 1
1.@ConfigurationProperties
该注解可以将配置文件中配置的每一个属性的值,通过set方法映射到被注释的组件中(因此不可以缺少setter方法)
/**
* 批量注入、松散绑定、数据校验、复杂类型封装
*/
@Component
@ConfigurationProperties(prefix = "person") //批量注入
public class Person {
private String lastName;
private Integer age;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;//复杂类型封装
public void setLastName(String lastName) {
this.lastName = lastName;
}
......
}
public class Dog {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
2.@Value
@Component
public class Person {
@Value("${person.lastName}")//从环境变量、配置文件中获取值
private String lastName;
@Value("#{11*2}")//使用SpEL表达式
private Integer age;
private Date birth;
@Value("${person.maps}")//不支持复杂类型,报错
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
......
}
3.@PropertySource、@ImportResource、@Bean
//指明当前类为配置类,替代之前的Spring配置文件
@Configuration
//加载指定的配置文件
@PropertySource(value = {"classpath:person.properties"})
//SpringBoot项目没有Spring的配置文件,若要想自己编写Spring配置文件加载并生效,需要使用@ImportResoure注解标注在一个配置类上
@ImportResource(locations = {"classpath:application.xml"})
public class MyAppConfig {
//注册bean,默认是方法名作为id
@Bean
public Person person() {
return new Person();
}