Spring boot 激活 profile的几种方式
-
在配置文件中直接指定
spring.profiles.active=test
这种方式非常不灵活,在实际开发部不太会使用到
-
使用占位符,在打包时替换,以mavne为例:
首先在配置文件中增加:
spring.profiles.active=@package.target@
在pom.xml中增加不同环境打包的配置:
<profiles> <profile> <id>dev</id><!-- 开发环境 --> <properties> <package.target>dev</package.target> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency> </dependencies> </profile> <profile> <id>prod</id><!-- 生产环境 --> <properties> <package.target>prod</package.target> </properties> </profile> <profile> <id>test</id><!-- 测试环境 --> <properties> <package.target>test</package.target> </properties> <dependencies> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency> </dependencies> </profile> </profiles> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering><!-- 使用package.target值,替换配置文件中 @package.target@ --> </resource> </resources> </build>
执行打包命令:
mvn package -Ptest
缺点:每次打包都要指定profile
-
JVM参数方式:
java命令行:
java -jar app.jar --spring.profiles.active=dev
tomcat 中 catalina.bat(.sh中不用“set”) 添加JAVA_OPS。通过设置active选择不同配置文件:
set JAVA_OPTS="-Dspring.profiles.active=test"
eclipse 中启动tomcat。项目右键 run as –> run configuration–>Arguments–> VM arguments中添加。
-Dspring.profiles.active="dev"
-
web.xml方式
<init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param>
-
标注方式(junit单元测试非常实用)
@ActiveProfiles({"unittest","productprofile"})
-
ENV方式(建议使用此方式)
系统环境变量SPRING_PROFILES_ACTIVE(注意:是大写)
优点:
- 应用不需要关注环境,环境应该有主机或者容器来定义;
- 一台主机部署多个应用不需要在每个Tomcat的setenv.sh里面增加配置,或者在每个启动脚本里去增加:-Dspring.profiles.active=prod。本地Windows调试的时候,也不想在eclipse里去设置环境变量,随便右键debug即可;
- 只需要打一个包就可以在所有环境运行,可以避免因打错包或部署错包造成的一系列问题。