SpringBoot中的@EnableConfigurationProperties注解详细解析
1.概述
@EnableConfigurationProperties注解的作用是:使 使用 @ConfigurationProperties 注解的类生效。
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component或者实现了@Component的其他注解,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
简单点说@EnableConfigurationProperties的功能类似于@Component。
2.测试
2.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 {
}
@RestController
public class ConfigurationPropertiesController {
@Autowired
private HelloServiceProperties helloServiceProperties;
@RequestMapping("/getObjectProperties")
public Object getObjectProperties () {
System.out.println(helloServiceProperties.getMsg());
return myConfigTest.getProperties();
}
}配置文件application.properties
service.properties.name=my-test-name service.properties.ip=192.168.1.1 service.user=kayle service.port=8080
一切正常,但是 HelloServiceAutoConfiguration 头部不使用 @EnableConfigurationProperties,测访问报错。
2.2 使用 @Component 注册
不使用 @EnableConfigurationProperties 进行注册,使用 @Component 注册
@ConfigurationProperties(prefix = "service.properties")
@Component
public 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 中。
3.项目中的使用场景
如下,在配置类NacosConfigAutoConfiguration的头上加注解@EnableConfigurationProperties(NacosConfigProperties.class),
而在NacosConfigProperties配置类本身并没有实现了@Component相关的注解,也就是说运行项目时,不会直接把NacosConfigProperties配置类注入到Spring 容器中,而是在执行NacosConfigAutoConfiguration这个配置类时才会去把NacosConfigProperties类注入到spring

如下,NacosConfigProperties类本身并没有@Component相关注解:

到此这篇关于SpringBoot中的@EnableConfigurationProperties注解详细解析的文章就介绍到这了,更多相关@EnableConfigurationProperties注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringData JPA中查询接口Repository的使用
本文主要介绍了SpringData JPA中查询接口Repository的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-07-07
JDK1.8使用的垃圾回收器和执行GC的时长以及GC的频率方式
这篇文章主要介绍了JDK1.8使用的垃圾回收器和执行GC的时长以及GC的频率方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-05-05
关于Spring MVC框架中拦截器Interceptor的使用解读
这篇文章主要介绍了关于Spring MVC框架中拦截器Interceptor的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-07-07
盘点SpringBoot中@Async注解的遇到的坑点及解决办法
SpringBoot是一个流行的Java开发框架,在异步编程方面,Spring Boot提供了@Async注解,它能够让方法异步执行,然而,在使用@Async注解时,有一些潜在的坑需要注意,本文将深入探讨Spring Boot中使用@Async注解时可能遇到的8大坑点,并提供相应的解决方案2024-03-03


最新评论