关于 @EnableConfigurationProperties 注解

作者 : 开心源码 本文共1953个字,预计阅读时间需要5分钟 发布时间: 2022-05-13 共357人阅读

先说作用:

@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的类生效。

说明:

假如一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
测试发现 @ConfigurationProperties 与 @EnableConfigurationProperties 关系特别大。

测试证实:
@ConfigurationProperties 与 @EnableConfigurationProperties 的关系。

@EnableConfigurationProperties 文档中解释:
当@EnableConfigurationProperties注解应用到你的@Configuration时, 任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。 这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。

测试发现:
1.使用 @EnableConfigurationProperties 进行注册

@ConfigurationProperties(prefix = "service.properties")public class HelloServiceProperties {    private static final String SERVICE_NAME = "test-service";    private String msg = SERVICE_NAME;       set/get}@Configuration@EnableConfigurationProperties(HelloServiceProperties.class)@ConditionalOnClass(HelloService.class)@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)public class HelloServiceAutoConfiguration {}@RestControllerpublic class ConfigurationPropertiesController {    @Autowired    private HelloServiceProperties helloServiceProperties;    @RequestMapping("/getObjectProperties")    public Object getObjectProperties () {        System.out.println(helloServiceProperties.getMsg());        return myConfigTest.getProperties();    }}

自动配置设置

service.properties.name=my-test-nameservice.properties.ip=192.168.1.1service.user=kayleservice.port=8080

一切正常,但是 HelloServiceAutoConfiguration 头部不使用 @EnableConfigurationProperties,测访问报错。

2.不使用 @EnableConfigurationProperties 进行注册,使用 @Component 注册

@ConfigurationProperties(prefix = "service.properties")@Componentpublic class HelloServiceProperties {    private static final String SERVICE_NAME = "test-service";    private String msg = SERVICE_NAME;    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

Controller 不变,一切正常,假如注释掉 @Component 测启动报错。
由此证实,两种方式都是将被 @ConfigurationProperties 修饰的类,加载到 Spring Env 中。

>推荐一下我的公众号: 【geekjc】,一起学习交流编程知识,分享经验,各种有趣的事,更多精彩内容,扫码进入小程序。

tuiguang.png

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 关于 @EnableConfigurationProperties 注解

发表回复