Spring中的@EnableConfigurationProperties使用方式以及作用詳解
@ConfigurationProperties
在@ConfigurationProperties的使用,把配置類的屬性與yml配置文件綁定起來的時候,還需要加上@Component注解才能綁定并注入IOC容器中,若不加上@Component,則會無效。
@EnableConfigurationProperties的作用:則是將讓使用了 @ConfigurationProperties 注解的配置類生效,將該類注入到 IOC 容器中,交由 IOC 容器進(jìn)行管理,此時則不用再配置類上加上@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);
}
}
結(jié)果圖:

2. @EnableConfigurationProperties的使用
當(dāng)去掉配置類的@Component時候,則會報(bào)下面錯誤提示:

在測試代碼上加上@EnableConfigurationProperties,參數(shù)指定那個配置類,該配置類上必須得有@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);
}
}
結(jié)果圖,仍然可以綁定

3. 為什么會有@EnableConfigurationProperties出現(xiàn)呢?
- 有的人可能會問,直接在配置類上加@Component注解,不就可以了嗎,為什么還要有@EnableConfigurationProperties出現(xiàn)呢?
- 敬請期待,待我寫到EnableAutoConfiguration自動裝配的時候,會豁然開朗滴。
到此這篇關(guān)于Spring中的@EnableConfigurationProperties使用方式以及作用詳解的文章就介紹到這了,更多相關(guān)@EnableConfigurationProperties的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot項(xiàng)目實(shí)現(xiàn)定時備份數(shù)據(jù)庫導(dǎo)出sql文件方式
這篇文章主要介紹了springboot項(xiàng)目實(shí)現(xiàn)定時備份數(shù)據(jù)庫導(dǎo)出sql文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-03-03
Mybatis-Spring連接mysql 8.0配置步驟出錯的解決方法
這篇文章主要為大家詳細(xì)介紹了Mybatis-Spring連接mysql 8.0配置步驟出錯的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06
springboot實(shí)現(xiàn)返回視圖而不是string的方法
這篇文章主要介紹了springboot實(shí)現(xiàn)返回視圖而不是string的方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
Springboot集成Sentinel?組件實(shí)現(xiàn)基本限流功能(快速入門)
Sentinel是阿里巴巴開發(fā)的面向云原生微服務(wù)的高可用流控防護(hù)組件,支持流量控制、熔斷降級、系統(tǒng)負(fù)載保護(hù)等多維度防護(hù),適用于秒殺、消息削峰填谷等場景,本文給大家介紹Springboot集成Sentinel組件實(shí)現(xiàn)基本限流功能,感興趣的朋友跟隨小編一起看看吧2025-12-12

