@ConfigurationProperties注解和@Value注解的区别

都是读取配置文件属性

1.  @ConfigurationProperties(prefix = "person")读取多个属性

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    String LastName;
    int age;
    boolean boss;
    Date birth;
    Map<String, String> maps;
    List<String> list;
    Dog dog;
prefix = "person" 读取前缀为person的属性的值.
yaml文件对应的属性值:
person:
  LastName: 飞
  age: 12
  boss: true
  birth: 2019/6/15
  maps: {key1:value1,key2:value2}
  list: [1,2,3,4,5]
  dog:
    name: 旺财
    age: ${random.int[20]}
 

1.  @value读取单个属性

@Component
public class Person1 {
    @Value("${person.last-name}")
    String LastName;
    //@Value("${person.age}")
   @Value("#{12*2}")
int age; @Value("${person.boss}") boolean boss; @Value("${person.birth}") Date birth; Map<String, String> maps; @Value("${person.list}") List<String> list; Dog dog;

注意事项:maps 和dog 不能使用@value注解,@Value不支持复杂类型

     

 application.properties文件配置

person.last-name=飞
person.age=12
person.boss=true
person.birth=2019/6/15
person.maps.key1=value1
person.maps.key2=value2
person.list=dog,cat
person.dog.name=${person.last-name}_你好
person.dog.age=${random.int(14)}

 两者获取值的比较(都能从properties和yaml获值)

  @ConfigurationProperties @value
功能 批量注入配置文件的属性 一个个指定
松散绑定(松散语法) 支持 不支持
SPEL 不支持 支持(计算,如上age的值所示)
JSR303数据校验 支持 (邮箱验证) 不支持
复杂类型封装 支持 不支持

显然,前者支持松绑定的特性更强大,所以在实际开发中建议使用@ConfigurationProperties来读取自定义属性。

猜你喜欢

转载自www.cnblogs.com/lh-cml/p/11026896.html