Spring中的@EnableConfigurationProperties使用方式以及作用詳解
@ConfigurationProperties
在@ConfigurationProperties的使用,把配置類的屬性與yml配置文件綁定起來的時候,還需要加上@Component注解才能綁定并注入IOC容器中,若不加上@Component,則會無效。
@EnableConfigurationProperties的作用:則是將讓使用了 @ConfigurationProperties 注解的配置類生效,將該類注入到 IOC 容器中,交由 IOC 容器進行管理,此時則不用再配置類上加上@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); } }
結果圖:
2. @EnableConfigurationProperties的使用
當去掉配置類的@Component時候,則會報下面錯誤提示:
在測試代碼上加上@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); } }
結果圖,仍然可以綁定
3. 為什么會有@EnableConfigurationProperties出現(xiàn)呢?
- 有的人可能會問,直接在配置類上加@Component注解,不就可以了嗎,為什么還要有@EnableConfigurationProperties出現(xiàn)呢?
- 敬請期待,待我寫到EnableAutoConfiguration自動裝配的時候,會豁然開朗滴。
到此這篇關于Spring中的@EnableConfigurationProperties使用方式以及作用詳解的文章就介紹到這了,更多相關@EnableConfigurationProperties的使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合Redis實現(xiàn)刷票過濾功能
隨著互聯(lián)網(wǎng)的不斷發(fā)展,網(wǎng)站或APP的用戶流量增加,也衍生出了一些惡意刷量等問題,給數(shù)據(jù)分析及運營帶來極大的困難,所以本文使用SpringBoot和Redis實現(xiàn)一個刷票過濾功能,需要的可以參考一下2023-06-06Java之next()、nextLine()區(qū)別及問題解決
這篇文章主要介紹了Java之next()、nextLine()區(qū)別及問題解決,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08Java使用pdfbox實現(xiàn)給pdf文件加圖片水印
有時候需要給pdf加水印,市面上工具都是收費的要會員,還是自食其力吧;嘗試過 spire.pdf.free 那個超過10頁就不行了!所以本文還是使用了pdfbox,感興趣的可以了解一下2022-11-11