主题列表:juejin, github, smartblue, cyanosis, channing-cyan, fancy, hydrogen, condensed-night-purple, greenwillow
贡献主题:https://github.com/xitu/juejin-markdown-themes
theme: juejin
highlight:
一、引言
在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 信息的属性列表。
这时再去配置文件中输入,就能有自动提示的效果。
博客介绍了项目中读取配置信息的问题,官方推荐用注解将配置属性映射到类属性上。还给出三种运行时读取配置文件内容的方式,包括注解于映射类、注解于方法、注解于映射类和配置类,同时提到添加插件依赖可实现配置文件自动提示。
2666

被折叠的 条评论
为什么被折叠?



