@ConfigurationProperties和@EnableConfigurationProperties配合使用


@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]

---------------------

原文:https://blog.csdn.net/u010502101/article/details/78758330

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM