开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 1 天,点击查看活动详情
ConfigurationProperties 使用方法
基本介绍
- @ConfigurationProperties 和 @Value 注解类似,用于获取配置文件中的属性定义并绑定到 Java Bean 或属性中
- @ConfigurationProperties 适用于所有具有相同前缀的分层属性,对于
.yml
和.properties
配置文件均可使用 - @ConfigurationProperties 绑定配置文件的规则比较松散,当配置类中定义 hostName 属性时,支持如下的配置规则:
- hostName
- hostname
- host_name
- host-name
- HOST_NAME
@ConfigurationProperties 注解的配置方法与 @Value 注解类似,可以参考文档SpringBoot 中 @Value 注解的使用方法
注入容器
@ConfigurationProperties 注解使用时需要配合 @Component、 @Configuration 等注解注释配置类,或者使用 @EnableConfigurationProperties 来指定配置文件类,这样配置类才可以注入到容器中,并在项目启动时注入配置。
- 不增加容器相关注解,则不会主动注入当前类的 bean,即不能显式启用
- @ConfigurationPropertiesScan("com.xxx.configurationproperties") 注释扫描配置属性类的自定义位置
- 可以使用 @PropertySource("classpath:xxx.yml") 注解自定义需要加载的配置文件
@ConfigurationProperties(prefix = "mysql")
@PropertySource("classpath:mysql.yml")
class PropertyConfiguration{
private String host;
}
SpringBoot 新版本使用
- Spring Boot 2.2 版本之后,Spring 通过类路径扫描查找并注册,此时只要能保证 @ConfigurationProperties 注解类被扫描到就会自动注入到容器中。
启动时校验 @ConfigurationProperties
- 如果希望配置参数在传入到应用中时有效的,可以通过在字段上添加 Bean Validation 相关注解,同时在类上添加 @Validated 注解
- 此时如果配置文件中没有配置对应内容且属性没有默认值,则在项目启动时会抛出异常信息
Bean Validation 相关注解的使用参考文档:SpringBoot 中使用 Validation 校验参数
ConfigurationProperties 使用问题
Spring Boot Configuration Annotation Processor not configured
问题描述:使用 @ConfigurationProperties 注解配置 SpringBoot 类时, IDEA 会提示内容:Spring Boot Configuration Annotation Processor not configured
- 指 Spring Boot 配置注解执行器没有配置,提示并不会影响实际项目的运行
- 如果想要移除异常提醒,则要为当前项目配置注解执行器,引入如下依赖信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 依赖引入后刷新 maven 依赖后即可
- 配置了注解执行器之后,当执行类中定义的属性和配置文件中的配置项就会进行关联
- 增加配置项时会弹出提示信息,可以使用快捷键自动补全配置
- 可以从配置文件中的配置项点击跳转到对应的配置类属性位置
Not registered via @EnableConfigurationProperties, marked as Spring component, or scanned via @ConfigurationPropertiesScan
问题描述:使用 @ConfigurationProperties 注解配置 SpringBoot 类时, 如果只使用该注解,则会报错该内容
- 可以通过增加 @Configuration、@Component、 @EnableConfigurationProperties(CorsProperties.class) 等注解来将类交由 Spring 容器处理,这样就不会报错了