SpringBoot-注解@ConfigurationProperties
参考文献
@ConfigurationProperties
@ConfigurationProperties
通过setter和构造器来设置field的值, 并且支持级联绑定属性- 配置文件中的属性个数可以和POJO中的field个数不一样, 如果这样那么field就使用默认值或是初始值
- 要想使
@ConfigurationProperties
生效, 可以通过@Component
, 或是在配置类上使用@EnableConfigurationProperties
, 并且指定value来使properties文件的值自动注入到对应pojo的属性中(同时会将该POJO注入到IoC) @ConfigurationProperties
不能与@EnableConfigurationProperties
一起标注在同一个类上- 可以在
@ConfigurationProperties
标注的类上使用@Validated
在来校验field的绑定 - 如果一个类标明了
@ConfigurationProperties
, 不会对内部类生效, 需要另外配置(因为内部类和外部类编译后是两不同的类) @NestedConfigurationProperties
没有任何实际功能, 用于表示@ConfigurationProperties
标注的类中的field
不是一个单一的值, 常与有初始值的复杂对象一起出现@ConfigurationProperties
可以和@PropertySource
一起使用, 这样就可以不用一个一个@Value
注意点
-
如果
@ConfigurationProperties
所注的类可以被Springboot
扫描并添加进容器中作为Bean
(比如使用@Component
等注解,或者配置扫描该类所在包等手段),那么Spring
容器会自动使该类上的@ConfigurationProperties
生效,创建一个该类的实例,然后把对应配置属性绑定进该实例,再把该实例作为Bean
添加进Spring
容器。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28package com.med3d.athena.propreties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.stereotype.Component;
/**
* 系统配置
*/
public class BusinessProperties {
/**
* 数据相关配置
*/
private DataProperties dataProperties;
/**
* OSS配置
*/
private OssProperties ossProperties;
} -
如果该类只使用了
@ConfigurationProperties
注解,然后该类没有在扫描路径下或者没有使用@Component
等注解,导致无法被扫描为Bean,那么就必须在配置类上使用@EnableConfigurationProperties
注解去指定这个类,这个时候就会让该类上的@ConfigurationProperties
生效,然后作为Bean
添加进Spring
容器中1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class BusinessProperties {
/**
* 数据相关配置
*/
private DataProperties dataProperties;
}
public class BusinessConfiguration {
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 HoleLin's Blog!