一、手动方法: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 prod4、测试接口:
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指定改为
spring.profiles.active=@spring.profiles.active@这时候打包使用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: