器 | Spring自定义配置属性 @ConfigurationProperties
一、引言
在Spring
项目中,经常要读取到配置信息,我们常用的方式为@value
注解为类中的Filed
赋值,但是这种方式是比较随意,填写配置时并不知配置的字段类型和默认值,容易出错;而且后期维护起来也很麻烦。Spring
官方推荐使用@ConfigurationProperties
注解将配置中的属性映射到bean
中的属性上。
二、实践
不管以怎么样的方式完成在运行时读取配置中的内容,总是要按照以下的步骤进行:
- 映射配置中的属性和
bean
类中的属性 - 将
bean
类注入到容器进行管理,使其正式成为bean
预设配置文件中有如下内容
biz:
enable: true
sub:
enable: true
max: 100
name: 'bizsub'
现在需要读取配置文件的这段内容,有以下三种方式能做到。
1.@ConfigurationProperties
和@Component
注解于映射类
@ConfigurationProperties
完成属性的映射,@Component
完成标识类为bean
。
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "biz")
public class BizProperties {
private boolean enable;
@Setter
@Getter
@Component
@ConfigurationProperties(prefix = "biz.sub")
public static class BizSubProperties{
private boolean enable;
private String name;
private long max;
}
}
2.@ConfigurationProperties
和@bean
注解于方法
@ConfigurationProperties 完成属性的映射,
@bean
完成标识类为bean
。
属性映射类
@Setter
@Getter
public class BizProperties {
private boolean enable;
@Setter
@Getter
public static class BizSubProperties{
private boolean enable;
private String name;
private long max;
}
}
在添加注解@configuration
配置类中添加方法
@Bean
@ConfigurationProperties(prefix = "biz")
BizProperties bizProperties() {
return new BizProperties();
}
@Bean
@ConfigurationProperties(prefix = "biz.sub")
BizProperties.BizSubProperties bizSubProperties(){
return new BizProperties.BizSubProperties();
}
3.@ConfigurationProperties
注解于映射类,@EnableConfigurationProperties
注解于配置类
@ConfigurationProperties 完成属性的映射,
@EnableConfigurationProperties`` 注册该类为
bean`。
映射类添加注解@ConfigurationProperties
@Setter
@Getter
@ConfigurationProperties(prefix = "biz")
public class BizProperties {
private boolean enable;
@Setter
@Getter
@ConfigurationProperties(prefix = "biz.sub")
public static class BizSubProperties{
private boolean enable;
private String name;
private long max;
}
}
配置类上添加注解@EnableConfigurationProperties
@EnableConfigurationProperties({BizProperties.class,BizProperties.BizSubProperties.class})
通过上面的方式能达到运行时读取配置文件内容的目的,但是在文件中写配置时候,没有自动提示,查看配置字段类型的功能。要达到下图的提示效果
需要添加插件
spring-boot-configuration-processor
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
如果重新编译(或创建)项目,插件将在路径 target/classes/META-INF/spring-configuration-metadata-JSON
中创建一个 JSON
文件。该文件包含所有具有类型和 Javadoc 信息的属性列表。
这时再去配置文件中输入,就能有自动提示的效果。
转载自:https://juejin.cn/post/6896038809255804941