在类上使用 @ConfigurationProperties,就可以为属性注入值。
1、配置文件内容
application.properties (Spring Boot 全局配置文件)
# 配置 demo 的值
demo.last-name=lisi
demo.age=30
demo.birthday=1989/9/12
demo.boss=false
demo.salary=23000
demo.map.key1=value1
demo.map.key2=value2
demo.list=one, two, three
demo.data-demo.name=zhangsan
demo.data-demo.age=8
2、在类上使用 @ConfigurationProperties
@ConfigurationProperties(prefix = "demo")
@Component
public class Demo {
private String lastName;
private Integer age;
private Double salary;
private Boolean boss;
private Date birthday;
private Map<String, Object> map;
private List<String> list;
private DataDemo dataDemo;
private static String config;
// 这里没有将 setter 和 getter 放在这里,
// 但是实际代码必须有 setter 和 getter 方法,否则无法注入成功
使用 @Component 让 Demo 类称为 Spring 容器组件,如果该类不在 Spring 容器中,则无法使用 @ConfigurationProperties 注解。
使用 @ConfigurationProperties 的 prefix 找到配置文件中所有前缀为 demo 的配置,将这些值注入对应的属性中。