Spring boot 配置文件參數映射到配置類屬性


參考文章】:SpringBoot之@EnableConfigurationProperties分析

【參考文章】:在Spring Boot中使用 @ConfigurationProperties 注解, @EnableConfigurationProperties

1. pom

        <!-- 通過資源文件注入屬性配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

2. main方法上添加注解

  @EnableConfigurationProperties(配置類1.class)

  @EnableConfigurationProperties({配置類1.class,配置類2.class})

  該注解是用來開啟對@ConfigurationProperties注解配置Bean的支持,也就是@EnableConfigurationProperties注解告訴Spring Boot 能支持@ConfigurationProperties。

@SpringBootApplication
@EnableConfigurationProperties(SystemConfig.class)
public class BootApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BootApplication.class, args);
        System.out.println("start ok");
    }

3. 配置類

  配置參數在 application.yml 文件中,系統自動讀取該文件,所以不必指定配置文件;

  @ConfigurationProperties (prefix = "system",ignoreInvalidFields = false ,ignoreUnknownFields = true) 

  prefix :表示參數 key 的前綴;

  ignoreInvalidFields :忽略無效的屬性,默認為 false;

  ignoreUnknownFields :忽略未知的屬性,默認為 true;

  如果需要指定配置文件,則需要使用添加 @PropertySource 注解(測試時讀取不到配置文件,待解決);

  @PropertySource(value = "filepath",encoding = "utf8",ignoreResourceNotFound = false)

  value:文件路徑;

  encoding:文件編碼格式;

  ignoreResourceNotFound:忽略未找到的資源文件,默認為false;

@ConfigurationProperties(prefix = "system")
public class SystemConfig  {
    private Integer type;

    public SystemConfig() {
        System.out.println("SystemConfig");
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }
}

4. 配置文件

4.1 yml 文件

system:
  type: 2

 

4.2 properties 文件

system.type=2

 

5. 常見問題

5.1 是否添加@Configuration 注解(原因暫不明確)

  初始化其他Bean時如果依賴配置類,則配置類不能添加@Configuration注解,否則spring會提示有兩個bean,必須指定一個bean;

  實例化其他Bean時如果不依賴配置類,配置類添加@Configuration注解也可以正常運行;


免責聲明!

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



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