@Value 获取值和 @ConfigurationProperties

spring-boot配置文件分享

application.properties 和 application.yml 的区别:

相同点:配置文件yml还是properties他们都能获取到值;

application.properties 配置文件

person.last-name=张三
person.age=18
person.birth=2019/10/10
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=狗狗
person.dog.age=15

application.yml 配置文件

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2019/9/9
  maps: {k1: v1,k2: 12}
  lists:
    - lisi
    - wangwu
  dog:
    name: 旺财
    age: 2

@Value 获取值和 @ConfigurationProperties 获取值比较

@ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个一个指定获取
松散绑定(松散语法) 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持

松散绑定(松散语法)

public class Person {

    @Value("${person.last-name}")
    private String lastName;
    @Value("#{11*2}")
    private Integer age;
    @Value("true")
    private boolean boss;
    private Date birth;

    private Map maps;
    private List lists;
    private Dog dog;
}

Person{lastName='张三', age=22, boss=true, birth=null, maps=null, lists=null, dog=null}
 
  

SpEL

@Value("#{11*2}")
private Integer age;


直接在配置文件引用表达式:
person.age=#{11*2}  //报错,格式转换异常

JSR303数据校验

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

//    @Value("${person.last-name}")
    @Email
    private String lastName;
//    @Value("#{11*2}")
    private Integer age;
//    @Value("true")
    private boolean boss;
    private Date birth;

    private Map maps;
    private List lists;
    private Dog dog;


//配合@Component使用
//运行结果: 报错,Reason: 不是一个合法的电子邮件地址
 
  

复杂类型封装:

@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

//    @Value("${person.last-name}")
//    @Email
    private String lastName;
//    @Value("#{11*2}")
    private Integer age;
//    @Value("true")
    private boolean boss;
    private Date birth;

//    @Value("${person.maps}")
    private Map maps;
    private List lists;
    private Dog dog;
 
  

总结:**

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;

如果说,我们专门编写了一个javaBean来和配置文件进行映射,就直接使用@ConfigurationProperties

@ConfigurationProperties 和 @PropertySource(value = {“classpath:person.properties”})

@ConfigurationProperties(prefix = “person”) 默认是从全局配置文件中获取值的,但当所有东西都配置在配置文件时,内容就会比较多,配置文件也会变得雍肿,这时就需要把相应的配置文件提取出来,用 @PropertySource 来获取指定的配置文件

person.properties:

person.last-name=李四
person.age=18
person.birth=2019/10/10
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=狗狗
person.dog.age=15

你可能感兴趣的:(@Value 获取值和 @ConfigurationProperties)