230118_50_SpringBoot入门
- yaml配置文件中,支持占位符配置
person:
name: bill${random.int}
age: 4
happy: true
birth: 2023/01/15
maps: {k1: v1,k2: v2}
hello: hello
lists:
- cat
- dog
- fish
dog:
name: ${person.hello:hi}
age: 2
- person
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
...
}
- 测试结果
- yaml和properties对比
1、@ConfigurationProperties只需要写一次即可 , @Value则需要每个字段都添加
2、松散绑定:这个什么意思呢? 比如我的yml中写的last-name,这个和lastName是一样的, - 后面跟着的字母默认是大写的。这就是松散绑定。
测试:
- Student类
package com.bill;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Auther: wangchunwen
* @Date: 2023/1/18 - 01 - 18 - 22:55
* @Description: com.bill
* @version: 1.0
*/
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String firstName;
private Integer id;
public Student(){
}
public Student(String firstName, Integer id) {
this.firstName = firstName;
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"firstName='" + firstName + '\'' +
", id=" + id +
'}';
}
}
student:
first-name: tom
id: 000001
测试结果:
3、JSR303数据校验 , 这个就是我们可以在字段是增加一层过滤器验证 , 可以保证数据的合法性。
- 以Student类为例,通过注解@Validated实现校验,不同的校验有不通的注解
@Component
@ConfigurationProperties(prefix = "student")
@Validated
public class Student {
@Email(message = "名字格式错误")
private String firstName;
private Integer id;
...
}
- 校验注解
4、复杂类型封装,yml中可以封装对象 , 使用value就不支持
结论:
配置yml和配置properties都可以获取到值 , 强烈推荐 yml;
如果我们在某个业务中,只需要获取配置文件中的某个值,可以使用一下 @value;
如果说,我们专门编写了一个JavaBean来和配置文件进行一一映射,就直接@configurationProperties!