@ConfigurationProperties 与 @EnableConfigurationProperties
@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的類生效。
如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component,那么在IOC容器中是獲取不到properties 配置文件轉化的bean。說白了 @EnableConfigurationProperties 相當于把使用 @ConfigurationProperties 的類進行了一次注入
@EnableConfigurationProperties 文檔中解釋:
當@EnableConfigurationProperties注解應用到你的@Configuration時, 任何被@ConfigurationProperties注解的beans將自動被Environment屬性配置。 這種風格的配置特別適合與SpringApplication的外部YAML配置進行配合使用。
自動配置設置(只是在配置文件的)
service.properties.name=my-test-name service.properties.ip=192.168.1.1 service.user=kayle service.port=8080一切正常,但是 HelloServiceAutoConfiguration 頭部不使用 @EnableConfigurationProperties,測訪問報錯。
2.不使用 @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 中
總結
以上是生活随笔為你收集整理的@ConfigurationProperties 与 @EnableConfigurationProperties的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 国密算法 SM2 公钥加密 非对称加密
- 下一篇: SpringBoot 二维码生成base