SpringBoot+maven实现多环境配置

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搭建测试环境或者生产环境进行持续集成了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值