SpringBoot中的@EnableConfigurationProperties注解詳細解析
1.概述
@EnableConfigurationProperties注解的作用是:使 使用 @ConfigurationProperties 注解的類生效。
如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實現(xiàn)了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉(zhuǎn)化的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配置類本身并沒有實現(xiàn)了@Component相關(guān)的注解,也就是說運行項目時,不會直接把NacosConfigProperties配置類注入到Spring 容器中,而是在執(zhí)行NacosConfigAutoConfiguration這個配置類時才會去把NacosConfigProperties類注入到spring

如下,NacosConfigProperties類本身并沒有@Component相關(guān)注解:

到此這篇關(guān)于SpringBoot中的@EnableConfigurationProperties注解詳細解析的文章就介紹到這了,更多相關(guān)@EnableConfigurationProperties注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot集成Mybatis實現(xiàn)對多數(shù)據(jù)源訪問原理
本文主要分析討論在SpringBoot應(yīng)用中我們該如何配置SqlSessionFactoryBean對象,進而實現(xiàn)對多個不同的數(shù)據(jù)源的操縱,文章通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-11-11
Java的MyBatis+Spring框架中使用數(shù)據(jù)訪問對象DAO模式的方法
Data Access Object數(shù)據(jù)訪問對象模式在Java操作數(shù)據(jù)庫部分的程序設(shè)計中經(jīng)常被使用到,這里我們就來看一下Java的MyBatis+Spring框架中使用數(shù)據(jù)訪問對象DAO模式的方法:2016-06-06

