Spring Boot - Profile配置

Profile是什麼

Profile我也找不出合適的中文來定義,簡單來講,Profile就是Spring Boot能夠對不一樣環境或者指令來讀取不一樣的配置文件。java

Profile使用

假若有開發、測試、生產三個不一樣的環境,須要定義三個不一樣環境下的配置。mysql

基於properties文件類型

你能夠另外創建3個環境下的配置文件:spring

applcation.properties
application-dev.properties
application-test.properties
application-prod.propertiessql

而後在applcation.properties文件中指定當前的環境: spring.profiles.active=test
這時候讀取的就是application-test.properties文件。微信

基於yml文件類型

只須要一個applcation.yml文件就能搞定,推薦此方式。app

spring:
  profiles: 
    active: prod

---
spring: 
  profiles: dev  
  
server: 
  port: 8080  
  
---
spring: 
  profiles: test  
  
server: 
  port: 8081    
  
---
spring.profiles: prod
spring.profiles.include:
  - proddb
  - prodmq
  
server: 
  port: 8082      
  
---
spring: 
  profiles: proddb  
  
db:
  name: mysql   
  
---
spring: 
  profiles: prodmq   

mq: 
  address: localhost

此時讀取的就是prod的配置,prod包含proddb,prodmq,此時能夠讀取proddb,prodmq下的配置。spring-boot

也能夠同時激活三個配置。測試

spring.profiles.active: prod,proddb,prodmq

基於Java代碼

在JAVA配置代碼中也能夠加不一樣Profile下定義不一樣的配置文件,@Profile註解只能組合使用@Configuration和@Component註解。this

@Configuration
@Profile("prod")
public class ProductionConfiguration {

    // ...

}

指定Profile

main方法啓動方式:

// 在Eclipse Arguments裏面添加
--spring.profiles.active=prod

插件啓動方式:

spring-boot:run -Drun.profiles=prod

jar運行方式:

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 & Cloud 最強技術教程

掃描關注咱們的微信公衆號,乾貨天天更新。

image

相關文章
相關標籤/搜索