1. 程式人生 > >SpringBoot-配置檔案詳解之自定義配置檔案

SpringBoot-配置檔案詳解之自定義配置檔案

今天我們一起來學習一下如何自定義配置檔案,在這之前我們可能會把配置項寫在application.properties或者application.yml中。這是springboot預設讀取的配置檔案,但是有時候我們需要自定義配置檔案用於配置特定需求的配置項。比如我們在classpath下建一個test.properties檔案:

然後將該配置檔案配置項的值用一個javabean來接收: 

@Component
@PropertySource(value = "classpath:test.properties", encoding = "UTF-8")
@ConfigurationProperties(prefix = "custom.properties")
public class CustomPropertiesFile {

  @Value("${year:2018}")
  private Integer year;

  @Value("${month:1}")
  private Integer month;

  public Integer getYear() {
    return year;
  }

  public void setYear(Integer year) {
    this.year = year;
  }

  public Integer getMonth() {
    return month;
  }

  public void setMonth(Integer month) {
    this.month = month;
  }

}

注意:

SpringBoot1.4及之前的版本中,要實現自定義properties配置檔案與JavaBean的對映,只需要在配置檔案對應的JavaBean上增加@ConfigurationProperties(locations="classpath:test.properties", prefix="custom.properties")這個註解,並在專案啟動類上增加@EnableConfigurationProperties啟動配置即可。但是在之後的版本中,@ConfigurationProperties註解不再提供locations屬性,所以無法實現對映。

解決這個問題,只需要在配置檔案對應的JavaBean

上增加:

  • @Component
  • @ConfigurationProperties(prefix = "custom.properties")
  • @PropertySource(value = "classpath:test.properties", encoding = "UTF-8") 

這三個註解即可,也不需要在專案啟動類上增加@EnableConfigurationProperties這個註解(如果此時在啟動類上將配置類新增到@EnableConfigurationProperties註解裡,則會報錯。然後我們寫一個簡單的controller類測試一下:

@RestController
@RequestMapping("/test/*")
public class CustomPropertiesFileController {

  @Autowired
  private CustomPropertiesFile file;

  @RequestMapping("getProperties")
  public String getProperties() {
    return file.getYear() + ":" + file.getMonth();
  }
}

啟動入口類,通過瀏覽器訪問: