Spring Boot 關於 @EnableConfigurationProperties 註解 —— 使用 @ConfigurationProperties 註解的類生效。

先說作用:

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

說明:

如果一個配置類只配置@ConfigurationProperties註解,而沒有使用@Component,那麼在IOC容器中是獲取不到properties 配置文件轉化的bean。說白了 @EnableConfigurationProperties 相當於把使用 @ConfigurationProperties 的類進行了一次注入。
測試發現 @ConfigurationProperties 與 @EnableConfigurationProperties 關係特別大。

測試證明:
@ConfigurationProperties@EnableConfigurationProperties 的關係。

@EnableConfigurationProperties 文檔中解釋:
@EnableConfigurationProperties註解應用到你的@Configuration時, 任何被@ConfigurationProperties註解的beans將自動被Environment屬性配置。 這種風格的配置特別適合與SpringApplication的外部YAML配置進行配合使用。

測試發現:
1.使用 @EnableConfigurationProperties 進行註冊

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

自動配置設置

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 中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章