配置文件
person:
lastName: hello
age: 18
boss: true
birth: 2017/12/12
map: {k1: v1,k2: v2}
lists:
- lisi
- guoyi
dog:
name: gou
age: 2
javaBean
将配置文件中配置的每一一个属性的值, 映射到这个组件中
@ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
prefix = "person": 配置文件中哪个下面的所有属性进行一一映射
只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;@Component是吧Person类注入到容器中
package com.example.demo.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
//geter seter 方法
}
Dog 类
public class Dog {
private String name;
private Integer age;
}
pom需要导入
<!-- 导入配置文件处理器,配置文件进行绑定就会有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
test类是这样的
@RestController
public class test {
@Autowired
Person person;
@RequestMapping("test")
public Person test(){
return person;
}
}
结果为:
如果不用ConfigurationProperties也可以用@Value("${person.lastName}")需要一个一个注入
#{}是spring的spel表达式,而${}是需要在配置文件中获取
@ConfigurationProperties和@Value区别:
数据校验:用Validated
这个可以加载制定的配置文件的值@PropertySource(value = "classpath:person.properties")而ConfigurationProperties需要加载默认是全局配置文件application.properties或application.yml
@PropertySource(value = {"classpath:person.properties"}) //不支持yml
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {