SpringBoot - @ConfigurationProperties 注解 vs @EnableConfigurationProperties 注解

回到顶部(go to top)

总结

@EnableConfigurationProperties 注解的作用是: 让使用了 @ConfigurationProperties 注解的类生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理。

如果没有使用@EnableConfigurationProperties 注解,那么@ConfigurationProperties需要搭配@Component使用,才能注入到IOC容器中。

 

回到顶部(go to top)

一、只使用 @ConfigurationProperties 注解

如果一个类只配置了 @ConfigurationProperties 注解,而没有使用 @Component 注解将该类加入到 IOC 容器中,那么它就不能完成 xxx.properties 配置文件和 Java Bean 的数据绑定

 

1、application.properties

xiaomao.name=xiaomaomao
xiaomao.age=27
 

2、MyConfigurationProperties.java

这个实体类中必须要加上 @Component ,使这个类注入到 IOC 容器中,否则就无法从容器中获取到这个类的对象实例

@Component
@ConfigurationProperties(prefix = "xiaomao")
public class MyConfigurationProperties {
    // 省略 get、set、toString方法
    private String name;
    private Integer age;
    private String gender;
}
 

3、HelloController.java

复制代码
@RestController
public class HelloController {
    @Autowired
    private MyConfigurationProperties config;
 
    @GetMapping("/config")
    private String testConfigurationProperties(){
        System.out.println(config);
        return "SUCCESS!!!";
    }
}
复制代码
 

4、测试结果

MyConfigurationProperties{name='xiaomaomao', age=27, gender='null'}
 

 

回到顶部(go to top)

二、使用 @EnableConfigurationProperties 注解

1、添加一个 HelloService 类

// 注入到 IOC 容器中,交由 Spring 进行管理
@Service
// 该注解的作用是使 MyConfigurationProperties 这个类上标注的 @ConfigurationProperties 注解生效,并且会自动将这个类注入到 IOC 容器中
@EnableConfigurationProperties(MyConfigurationProperties.class)
public class HelloServiceImpl implements HelloService {
}
 

2、MyConfigurationProperties.java

有了 @EnableConfigurationProperties 注解之后该实体类就不需要加上 @Component 注解了

@ConfigurationProperties(prefix = "xiaomao")
public class MyConfigurationProperties {
    // 省略 get、set、toString方法
    private String name;
    private Integer age;
    private String gender;
}
 

3、HelloController.java

复制代码
@RestController
public class HelloController {
    @Autowired
    private MyConfigurationProperties config;
 
    @GetMapping("/config")
    private String testConfigurationProperties(){
        System.out.println(config);
        return "SUCCESS!!!";
    }
}
复制代码
 

4、测试结果

MyConfigurationProperties{name='xiaomaomao', age=27, gender='null'}
 

 

回到顶部(go to top)

参考文献

https://www.jianshu.com/p/7f54da1cb2eb 

https://www.cnblogs.com/xiaomaomao/p/13934688.html 

 

posted on   frank_cui  阅读(237)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

levels of contents
点击右上角即可分享
微信分享提示