SpringBoot中,將類中的屬性和配置文件中的配置進行綁定時出現以下的問題:
當使用@ConfigurationProperties時IDEA頂部出現這樣的提示:

按照提示點擊跳轉到官方文檔,接着在pom.xml中添加如下的配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
添加完后的效果是,當你寫配置文件(yml,properties配置文件)時會有相關的提示
上面弄完后@ConfigurationProperties下面還有報錯,按照提示可以看到
Not registered via @EnableConfigurationProperties or marked as Spring component,網上找到的博客有說要添加 @EnableConfigurationProperties(Person.class)【此時的Person是自定義的bean】,

添加后錯誤確實是沒了,但是在SpringBoot的單元測試時會看到如下的錯誤:Could not autowire. No beans of 'Person' type found
回到自定義的bean Person中,添加注解@Component,聲明將這個組件添加至容器中,這樣才可以被使用?
“只有這個組件是容器中的組件,才能使用容器提供的@ConfigurationProperties功能,”

關於@Component和@EnableConfigurationProperties找到一個討論,覺得應該有用,只是現在還不是很理解
https://www.imooc.com/qadetail/299025

確保添加了依賴 <dependency> <groupId> org.springframework.boot </groupId> <artifactId> spring-boot-configuration-processor </artifactId> <optional> true </optional> </dependency> 如果發現@ConfigurationPropertie不生效,有可能是項目的目錄結構問題,可以通過@EnableConfigurationProperties(ConnectionSettings.class)來明確指定需要用哪個實體類來裝載配置信息。 Spring boot 1.5以上去除了location屬性,可采用@Component的方式注冊為組件,然后使用@PropertySource來指定自定義的資源目錄。
記錄:通過@ConfigurationProperties獲取配置文件的相關配置屬性注入bean中
