javascript
Spring Boot - Profile不同环境配置
?
Profile是什么
Profile我也找不出合適的中文來定義,簡單來說,Profile就是Spring Boot可以對不同環境或者指令來讀取不同的配置文件。
?
Profile使用
假如有開發、測試、生產三個不同的環境,需要定義三個不同環境下的配置。
基于properties文件類型
你可以另外建立3個環境下的配置文件:
applcation.properties
application-dev.properties
application-test.properties
application-prod.properties
然后在applcation.properties文件中指定當前的環境spring.profiles.active=test,這時候讀取的就是application-test.properties文件。
?
基于yml文件類型
只需要一個applcation.yml文件就能搞定,推薦此方式。
spring:profiles:active: prod--- spring:profiles: dev ?server:port: 8080 ?--- spring:profiles: test ?server:port: 8081 ? ?--- spring.profiles: prod spring.profiles.include:- proddb- prodmqserver:port: 8082 ? ? ?--- spring:profiles: proddb ?db:name: mysql ?--- spring:profiles: prodmq ?mq:address: localhost此時讀取的就是prod的配置,prod包含proddb,prodmq,此時可以讀取proddb,prodmq下的配置。
也可以同時激活三個配置。
spring.profiles.active: prod,proddb,prodmq?
基于Java代碼
在JAVA配置代碼中也可以加不同Profile下定義不同的配置文件,@Profile注解只能組合使用@Configuration和@Component注解。
@Configuration @Profile("prod") public class ProductionConfiguration {// ...}?
指定Profile
main方法啟動方式:
// 在Eclipse Arguments里面添加
--spring.profiles.active=prod
插件啟動方式:
spring-boot:run -Drun.profiles=prodjar運行方式:
java -jar xx.jar --spring.profiles.active=prod 除了在配置文件和命令行中指定Profile,還可以在啟動類中寫死指定,通過SpringApplication.setAdditionalProfiles方法。SpringApplication.class
public void setAdditionalProfiles(String... profiles) {this.additionalProfiles = new LinkedHashSet<String>(Arrays.asList(profiles)); }?
總結
以上是生活随笔為你收集整理的Spring Boot - Profile不同环境配置的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot 配置加载顺序详解
- 下一篇: 一分钟开启Tomcat https支持