器 | Spring自定义配置属性 @ConfigurationProperties


主题列表: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 信息的属性列表。

这时再去配置文件中输入,就能有自动提示的效果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值