Spring中的@EnableConfigurationProperties使用方式以及作用详解
@ConfigurationProperties
在@ConfigurationProperties的使用,把配置类的属性与yml配置文件绑定起来的时候,还需要加上@Component注解才能绑定并注入IOC容器中,若不加上@Component,则会无效。
@EnableConfigurationProperties的作用:则是将让使用了 @ConfigurationProperties 注解的配置类生效,将该类注入到 IOC 容器中,交由 IOC 容器进行管理,此时则不用再配置类上加上@Component。
代码例子
1. @ConfigurationProperties的使用
(提外话:具体的yml文件字符串、List、Map的书写方式并使用@ConfigurationProperties注入配置类.)
配置类
@Component
@ConfigurationProperties(prefix = "demo")
@Data
public class DemoConfig {
private String userName;
private String age;
}yml配置文件
demo: user-name: hello age: 18
测试代码
@Component
public class demo implements ApplicationRunner {
@Autowired
DemoConfig demoConfig;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(demoConfig);
}
}
结果图:

2. @EnableConfigurationProperties的使用
当去掉配置类的@Component时候,则会报下面错误提示:

在测试代码上加上@EnableConfigurationProperties,参数指定那个配置类,该配置类上必须得有@ConfigurationProperties注解
@Component
@EnableConfigurationProperties(DemoConfig.class)
public class demo implements ApplicationRunner {
@Autowired
DemoConfig demoConfig;
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(demoConfig);
}
}
结果图,仍然可以绑定

3. 为什么会有@EnableConfigurationProperties出现呢?
- 有的人可能会问,直接在配置类上加@Component注解,不就可以了吗,为什么还要有@EnableConfigurationProperties出现呢?
- 敬请期待,待我写到EnableAutoConfiguration自动装配的时候,会豁然开朗滴。
到此这篇关于Spring中的@EnableConfigurationProperties使用方式以及作用详解的文章就介绍到这了,更多相关@EnableConfigurationProperties的使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
springboot项目实现定时备份数据库导出sql文件方式
这篇文章主要介绍了springboot项目实现定时备份数据库导出sql文件方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2025-03-03
Mybatis-Spring连接mysql 8.0配置步骤出错的解决方法
这篇文章主要为大家详细介绍了Mybatis-Spring连接mysql 8.0配置步骤出错的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2019-06-06
Springboot集成Sentinel 组件实现基本限流功能(快速入门)
Sentinel是阿里巴巴开发的面向云原生微服务的高可用流控防护组件,支持流量控制、熔断降级、系统负载保护等多维度防护,适用于秒杀、消息削峰填谷等场景,本文给大家介绍Springboot集成Sentinel组件实现基本限流功能,感兴趣的朋友跟随小编一起看看吧2025-12-12


最新评论