1.新建四个配置文件:
- application.yml
- application-dev.yml
- application-test.yml
- application-prod.yml
application.yml
spring:
profiles:
active: "@spring.profiles.active@"
此处为打war包,需要配合maven resource,如果打jar,则无需这样写,直接写对应的环
境名即可,如 active: test
application-dev.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/xxx?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: xxx
password: xxxxxxxx
application-test.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://测试环境ip:3306/xxx?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: xxx
password: xxxxxxxx
application-prod.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://生产环境ip:3306/xxx?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username: xxx
password: xxxxxxxx
2.war包的实现
打war包需要修改pom文件,修改build标签和profiles标签,加入:
<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>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>application*.yml</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<!--②-->
<filtering>true</filtering>
<includes>
<include>application.yml</include>
<include>application-${spring.profiles.active}.yml</include>
</includes>
</resource>
</resources>
</build>
打包方法:
mvn install //默认本地的包
mvn install -Ptest //打测试环境的包
mvn install -Pprod //打生成环境的包
这样maven会自动用pom文件中<spring.profiles.active></spring.profiles.active>的值替换yml文件中spring.profiles.active中的值。
3.Jar包的实现
配置pom:
<packaging>jar</packaging>
然后mvn package打出一个jar包xxx.jar
jar包用java -jar命令直接启动,无需依赖SpringBoot中的embedded-tomcat
java -jar xxx.jar --spring.profiles.active=dev //启动本地环境
java -jar xxx.jar --spring.profiles.active=test //启动测试环境
java -jar xxx.jar --spring.profiles.active=prod //启动生产环境
然后就可以非常方便的使用jenkins+maven搭建测试环境或者生产环境进行持续集成了。