一、application.(properties和yaml)的不同
推荐使用:yaml格式
yaml
# k=v
# 对空格要求十分高
# 普通的key-value
name: aguo
# 对象
student1:
name: aguo
age: 3
# 行内写法
student2: {name: aguo,age: 3}
# 数组
pets1:
- cat
- dog
- pig
pets2: [cat,pig,dog]
properties
# properties只能保存键值对
name=aguo
student.name=aguo
student.age=15
二、注解解释
@Component:标注一个类为Spring容器的Bean,(把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
@Value属性注入功能根据注入的内容来源可分为两类:通过配置文件的属性注入和通过非配置文件的属性注入。
@Autowired :它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
@ConfigurationProperties:作用是告诉springBoot,此类中的属性将与默认的全局配置文件中对应属性一一绑定。属性名必须是application.yml或application.properties。
【 prefix = "person"】表示与配置文件中哪个层级的属性进行绑定。
@PropertySource:指定资源文件读取的位置,
eg:@PropertySource(value = "classpath:文件名字")
@Validated:校验数据
三、@Value赋值方式
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Dog {
@Value("旺财")
private String name;
@Value("3")
private Integer age;
}
测试类
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog);
}
测试结果
四、@ConfigurationProperties赋值方式
@NoArgsConstructor
@AllArgsConstructor
@Data
@Component
@ConfigurationProperties(prefix = "person")
public class People {
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文件
person:
name: aguo
age: 15
happy: false
birth: 2021/12/11
maps: {k1: v1,k2: v2}
lists:
- code
- music
- girl
dog:
name: 旺财
age: 5
测试类
@Autowired
private People person;
@Test
void contextLoads() {
System.out.println(person);
}
测试结果
五、JSR303校验
@NoArgsConstructor
@AllArgsConstructor
@Data
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class People {
@Email(message = "邮箱格式错误")
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
}
六、松散绑定
people有一个字符串类型的属性firstName
people:
firstName: aguo
first-name: aguo
first_name: aguo
FIRST_NAME: aguo