1. 程式人生 > >Spring Boot+Profile實現不同環境讀取不同配置

Spring Boot+Profile實現不同環境讀取不同配置

images alt quest color ive 作用 讀取 ron 總結

文件結構如下:

技術分享

但是官方推薦放在config文件夾下。

作用:

不同環境的配置設置一個配置文件,例如:dev環境下的配置配置在application-dev.properties中。prod環境下的配置配置在application-prod.properties中。

使用:

1、在applicaiton.properties中指定,比如spring.profiles.active=dev

2、啟動時指定參數,比如java -jar xxx.jar --spring.profiles.active=dev

3、啟動時指定系統屬性,比如java -jar xxx.jar -Dspring.profiles.active=dev

使用技巧:

在application.properties中的變量可以通過這樣的方式獲取:

@Autowired  
private Environment env;  
          
@RequestMapping("/testProfile")  
public String testProfile(){  
    return env.getProperty("spring.profiles.active");  
}  

總結:

  1. 各個環境公共的配置寫在application.properties中,默認讀取這個。
  2. 各個模塊獨有的配置配置在自己的application-{xxx}.properties文件中,通過啟動參數--xxx或者系統屬性-Dxxx指定來加載,或者在application.properties中配置spring.profiles.active的項。
  3. 程序啟動時如果沒有任何指定,默認讀取application.properties;如果指定了那麽會讀取application-{xxx}.properties,會覆蓋application.properties的的項。

參考:

http://www.leftso.com/blog/111.html(這個說的比較詳細)

http://blog.csdn.net/lazycheerup/article/details/51915185

Spring Boot+Profile實現不同環境讀取不同配置