常用的几种激活profile的方式
- 在配置文件中直接指定
spring.profiles.active=test
- 使用占位符,在打包时替换,以mavne为例
maven中加入spring.profiles.active=@spring.profiles.active@
打包时执行以下命令,或者<profiles> <profile> <id>dev</id> <properties> <spring.profiles.active>dev</spring.profiles.active> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <spring.profiles.active>test</spring.profiles.active> </properties> </profile> <profile> <id>prod</id> <properties> <spring.profiles.active>prod</spring.profiles.active> </properties> </profile> </profiles>
IDEA右边直接勾选要选择的环境mvn package -Ptest
- JVM参数方式
java命令行:
或者IDEAjava -jar app.jar --spring.profiles.active=dev
- ENV方式(建议使用此方式)
具体使用哪个环境由服务器决定,通过在服务器(例如Tomcat)上的启动脚本里增加:-Dspring.profiles.active=prod来决定使用哪个环境。
优点是不再需要上线测试、生产时手动改环境了,只需要打一个包就可以在所有环境运行,可以避免因打错包或部署错包造成的一系列问题。
这是我项目启动Tomcat的脚本的配置,通过在启动脚本里指定要环境,可以动态选择要启动哪种配置文件
具体maven配置和上述第二种差不多,先在maven配置profile
<build>
<resources>
<resource>
<!-- 指定配置文件所在的resource目录 -->
<directory>src/main/resources</directory>
<includes>
<include>public/**</include>
<include>static/**</include>
<include>templates/**</include>
<!-- 选择要打包的配置文件和日志,当然也可以不加打包所有配置文件,然后由具体服务器来选择使用哪个 -->
<include>application-${spring.profiles.active}.yml</include>
<include>logback-${spring.profiles.active}.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>dev</id>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
配置文件变成如下格式