跟我学springboot(八)springboot全局配置文件之properties

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a303549861/article/details/82393213

1.配置读取

在application.properties有如下的文件配置:

person.last-name=张三
person.age=21
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=小狗
person.dog.age=15

1.1使用@ConfigurationProperties读取

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

1.2使用@Value读取

value=”字面量/${key}从环境变量、配置文件中获取值/#{SpEL}”

@Component
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<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

1.3松散绑定Relaxed binding

比如我们需要获取值person.first-name
1.使用@ConfigurationProperties支持Relaxed binding
写法都是可以获取到值的:
– person.firstName:使用标准方式
– person.first-name:大写用-
– person.first_name:大写用_
– PERSON_FIRST_NAME:
推荐系统属性使用这种写法
我们将配置文件改为:
person.lastName=张三
在实体bean中使用@ConfigurationProperties获取值依然可以获取到。
2.@Value则不支持

1.4 SpEl表达式支持

将配置文件中person.age=#{11*2}
使用@ConfigurationProperties则无法获取到年龄
使用@Value则可以识别表达式

1.5 JSR303进行配置文件值校验

@ConfigurationProperties支持校验
使用@Value则不支持

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

1.6 复杂类型封装

@ConfigurationProperties支持
person.maps.k1=v1
person.maps.k2=14
则可以自动封装map
使用@Value则不支持

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

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

3.使用场景

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

猜你喜欢

转载自blog.csdn.net/a303549861/article/details/82393213