Java配置多环境

原创
2020/05/23 13:40
阅读数 421

Java项目在开发过程中会有多个环境设置,比如开发环境、测试环境、生产环境等等,所以在项目中我们要去相应的做配置,而不是在部署的时候手动的去改配置。 以maven项目为例,介绍一下spring项目和springboot的配置方法。

spring项目

  • 配置文件

首先打开我们的项目,指定到resources目录下创建多个环境文件夹,例如上方的dev、test、online等等。在每个环境文件夹中创建自己的对应环境的配置文件:

  • 配置pom.xml

首先设置profiles,如下:

	<profiles>
		<profile>
			<id>dev</id>
			<properties>
				<profiles.active>dev</profiles.active>
			</properties>
			<activation>
				<activebydefault>true</activebydefault>
			</activation>
		</profile>
		<profile>
			<id>test</id>
			<properties>
				<profiles.active>test</profiles.active>
			</properties>
		</profile>
		<profile>
			<id>online</id>
			<properties>
				<profiles.active>online</profiles.active>
			</properties>
		</profile>
		<profile>
			<id>vip</id>
			<properties>
				<profiles.active>vip</profiles.active>
			</properties>
		</profile>
		<profile>
			<id>spdb</id>
			<properties>
				<profiles.active>spdb</profiles.active>
			</properties>
		</profile>
	</profiles>

其中profiles.active表示的是对应的环境文件夹的名字,activeByDefault代表默认的配置。 然后设置build.resources,如下:

		<resources>
			<resource>
				<directory>src/main/resources/${profiles.active}</directory>
			</resource>
		</resources>

这样就可以了。 然后使用maven打包时,使用:mvn package -P online,就可以打生产包了。

springboot项目

springboot项目要比spring简单得多:

首先在resources下创建多个application-XXX.properties文件,其中XXX表示这种环境,比如test、online等。 然后再创建一个application.properties文件:

就一行代码搞定。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部