1. 程式人生 > >Spring boot @ConfigurationProperties和@EnableConfigurationProperties 作用

Spring boot @ConfigurationProperties和@EnableConfigurationProperties 作用

本文轉載於https://blog.csdn.net/u010502101/article/details/78758330

@ConfigurationProperties註解主要用來把properties配置檔案轉化為bean來使用的,而@EnableConfigurationProperties註解的作用是@ConfigurationProperties註解生效。如果只配置@ConfigurationProperties註解,在IOC容器中是獲取不到properties配置檔案轉化的bean的。使用如下:

1、spring boot啟動時預設是載入application.properties配置檔案的,假設該配置檔案中內容為:

local.host=127.0.0.1
local.port=8080

2、建立一個類ComponentProperties,把配置檔案轉化為bean來使用。@ConfigurationProperties註解可以把properties檔案轉化為bean,然後使用@Component註解把該bean注入到IOC容器中。

package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
/*prefix定義配置檔案中屬性*/
@ConfigurationProperties(prefix="local")
public class ComponentProperties {

    /*host和port屬性必須保持與application.properties中的屬性一致*/
    private String host;
    private String port;

    public void setHost(String host) {
        this.host = host;
    }
    public void setPort(String port) {
        this.port = port;
    }

    @Override
    public String toString() {
        return "ComponentProperties [host=" + host + ", port=" + port + "]";
    }

}

3、用@EnableConfigurationProperties註解使@ConfigurationProperties生效,並從IOC容器中獲取bean。

package com.example.demo;
import org.springframework.boot.SpringApplication;
import 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

//@SpringBootApplication
@ComponentScan
/*@EnableConfigurationProperties註解是用來開啟對@ConfigurationProperties註解配置Bean的支援。
也就是@EnableConfigurationProperties註解告訴Spring Boot 使能支援@ConfigurationProperties*/
@EnableConfigurationProperties
public class Springboot3Application {

    public static void main(String[] args) throws Exception {

        ConfigurableApplicationContext context = SpringApplication.run(Springboot3Application.class, args);
        /*@ConfigurationProperties註解和@EnableConfigurationProperties配合使用*/
        System.out.println(context.getBean(ComponentProperties.class));
        context.close();
    }
}

啟動類如上,@ComponentScan註解預設掃描啟動類所在的包,該包下的類如果注入到了IOC容器中,那麼在該啟動類就能獲取注入的bean。然後用@EnableConfigurationProperties註解使@ConfigurationProperties註解生效。因此在該啟動類中就可以獲取剛才application.properties配置檔案轉化的bean了。另外,只使用@SpringBootApplication一個註解也是可以的,因為@SpringBootApplication註解中已經包含了@ComponentScan和@EnableAutoConfiguration註解,@EnableAutoConfiguration註解最終使ConfigurationPropertiesAutoConfiguration類上的@EnableAutoConfiguration生效。

4、輸出結果如下:

ComponentProperties [host=127.0.0.1, port=8080]