Springboot 之 @EnableConfigurationProperties 注解
@EnableConfigurationProperties 注解的作用是:
1、让使用了 @ConfigurationProperties 注解的类生效
2、将该类注入到 IOC 容器中,交由 IOC 容器进行管理
一、使用 @ConfigurationProperties + @Component 注解
如果一个类只配置了 @ConfigurationProperties 注解,而没有使用 @Component 注解将该类加入到 IOC 容器中,那么它就不能完成 xxx.properties 配置文件和 Java Bean 的数据绑定
1、application.properties
1 2 | xiaomao.name=xiaomaomao xiaomao.age= 27 |
2、MyConfigurationProperties 这个实体类中必须要加上 @Component ,使这个类注入到 IOC 容器中,否则就无法从容器中获取到这个类的对象实例
1 2 3 4 5 6 7 8 | @Component @ConfigurationProperties (prefix = "xiaomao" ) public class MyConfigurationProperties { // 省略 get、set、toString 方法 private String name; private Integer age; private String gender; } |
3、HelloController
1 2 3 4 5 6 7 8 9 10 11 | @RestController public class HelloController { @Autowired private MyConfigurationProperties config; @GetMapping ( "/config" ) private String testConfigurationProperties(){ System.out.println(config); return "SUCCESS!!!" ; } } |
4、测试结果
1 | MyConfigurationProperties{name= 'xiaomaomao' , age= 27 , gender= 'null' } |
二、使用 @EnableConfigurationProperties 注解
1、添加一个 HelloService 类
1 2 3 4 5 6 | // 注入到 IOC 容器中,交由 Spring 进行管理 @Service // 该注解的作用是使 MyConfigurationProperties 这个类上标注的 @ConfigurationProperties 注解生效,并且会自动将这个类注入到 IOC 容器中 @EnableConfigurationProperties (MyConfigurationProperties. class ) public class HelloServiceImpl implements HelloService { } |
2、MyConfigurationProperties 有了 @EnableConfigurationProperties 注解之后该实体类就不需要加上 @Component 注解了
1 2 3 4 5 6 7 | @ConfigurationProperties (prefix = "xiaomao" ) public class MyConfigurationProperties { // 省略 get、set、toString 方法 private String name; private Integer age; private String gender; } |
3、HelloController.java
1 2 3 4 5 6 7 8 9 10 11 | @RestController public class HelloController { @Autowired private MyConfigurationProperties config; @GetMapping ( "/config" ) private String testConfigurationProperties(){ System.out.println(config); return "SUCCESS!!!" ; } } |
4、测试结果
1 | MyConfigurationProperties{name= 'xiaomaomao' , age= 27 , gender= 'null' } |
三、结论
如果要使 xxx.properties 配置文件与 Java Bean 动态绑定,那么就必须将这个 Java Bean 加入到容器中,并且需要在该类上使用 @ConfigurationProperties 注解
@EnableConfigurationProperties(A.class)的作用就是如果 A 这个类上使用了 @ConfigurationProperties 注解,那么 A 这个类会与 xxx.properties 进行动态绑定,并且会将 A 这个类加入 IOC 容器中,并交由 IOC 容器进行管理
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~