關(guān)與 @EnableConfigurationProperties 注解

先說作用:

@EnableConfigurationProperties注解的作用是:使使用 @ConfigurationProperties 注解的類生效。

說明:

如果一個(gè)配置類只配置@ConfigurationProperties注解,而沒有使用@Component,那么在IOC容器中是獲取不到properties 配置文件轉(zhuǎn)化的bean。說白了 @EnableConfigurationProperties 相當(dāng)于把使用 @ConfigurationProperties 的類進(jìn)行了一次注入。
測試發(fā)現(xiàn) @ConfigurationProperties 與 @EnableConfigurationProperties 關(guān)系特別大。

測試證明:
@ConfigurationProperties@EnableConfigurationProperties 的關(guān)系。

@EnableConfigurationProperties 文檔中解釋:
當(dāng)@EnableConfigurationProperties注解應(yīng)用到你的@Configuration時(shí), 任何被@ConfigurationProperties注解的beans將自動(dòng)被Environment屬性配置。 這種風(fēng)格的配置特別適合與SpringApplication的外部YAML配置進(jìn)行配合使用。

測試發(fā)現(xiàn):
1.使用 @EnableConfigurationProperties 進(jìn)行注冊(cè)

@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();
    }
}

自動(dòng)配置設(shè)置

service.properties.name=my-test-name
service.properties.ip=192.168.1.1
service.user=kayle
service.port=8080

一切正常,但是 HelloServiceAutoConfiguration 頭部不使用 @EnableConfigurationProperties,測訪問報(bào)錯(cuò)。

2.不使用 @EnableConfigurationProperties 進(jìn)行注冊(cè),使用 @Component 注冊(cè)

@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 測啟動(dòng)報(bào)錯(cuò)。
由此證明,兩種方式都是將被 @ConfigurationProperties 修飾的類,加載到 Spring Env 中。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容