一、手動方法:springboot項目中,我們經常把一些變量參數寫在application.properties文件中,但是不同的環境參數可能不一樣,spring.profiles.active可以區分環境,如下例:
1、pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.profiles</groupId>
<artifactId>profiles-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
2、啓動類:
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProfilesApplication {
public static void main(String args[]){
SpringApplication.run(ProfilesApplication.class,args);
}
}
3、配置文件:
(1)總配置:
server.port= 8888
server.context-path=/profiles
spring.profiles.active=prod
zt.common = conmmon
(2)dev開發環境:
zt.profiles = this is dev
(3)test測試環境:
zt.profiles = this is test
(4)prod生產環境:
zt.profiles = this is prod
4、測試接口:
package com.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Value("${zt.common}")
private String common;
@Value("${zt.profiles}")
private String profilesStr;
@RequestMapping("/test")
public String getStr(){
return "公共:"+common+";環境:"+profilesStr;
}
}
如現在環境爲prod,postman測試下接口:
mvn clean package打包測試一下:
解壓打包後的jar包,
從application.properties中可以看到環境爲prod
這時候我們打包帶參數,如mvn clean package -Ptest、mvn clean package -Pdev、mvn clean package -Pprod,打包後的仍然是prod,就是說必須手動修改application.properties中的環境。
二、動態指定:
1、在pom中添加以下配置:
<profiles>
<!-- 測試環境 -->
<profile>
<id>test</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
<!-- 開發環境 -->
<profile>
<id>dev</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<!-- 生產環境 -->
<profile>
<id>prod</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
2、並把application.properties中的profiles指定改爲
[email protected]@
這時候打包使用mvn clean package -Ptest、mvn clean package -Pdev、mvn clean package -Pprod,打出來的就是指定環境的包了。pom文件中test一項默認是true,所以如果不指定環境直接使用mvn clean package打包就是test環境。
idea啓動則可以點擊右側的maven,選擇環境勾上,再啓動服務即可:
如我勾上prod:
啓動服務訪問的爲prod環境:
再去掉prod,勾上test:
重啓服務訪問的爲test: