SpringBoot Profile 多环境配置和打包

最近工作有一个需求通过 Spring boot 多环境配置实现,多环境配置打包作用很多,我这直接上步骤,分享怎样在 Spring boot 中配置多环境。

Spring Boot profile

创建 Spring Profile ,具体有多少种环境,就在项目pom.xml创建多少个 profile

<!-- Maven控制Spring Profile -->
	<profiles>
		<!--默认开启小桔充电-->
		<profile>
			<id>xiaoju</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<properties>
				<profileActive>xiaoju</profileActive>
			</properties>
			<build>
				<!-- 打包后文件名称:项目名-环境 -->
				<finalName>${project.artifactId}-${profileActive}</finalName>
			</build>
		</profile>
		<!--恒大-->
		<profile>
			<id>hengda</id>
			<properties>
				<profileActive>hengda</profileActive>
			</properties>
			<build>
				<!-- 打包后文件名称:项目名-环境 -->
				<finalName>${project.artifactId}-${profileActive}</finalName>
			</build>
		</profile>
	</profiles>

这里比较简单,它可以让我们快速切换配置文件,如上代码自行修改,创建完成在开发工具右边 Maven 菜单会看到如下图。

我们可以通过「勾选」确定要导入的配置文件,打包出对应配置文件的包。

像之前 Spring boot灵活切换配置文件,static静态变量配置文件读取 ,其实我都是手动修改代码切换的,那就有点太粗糙。

编写配置文件

本身 resources 下有一个 application.yml ,里面存放各种配置信息,比如端口、数据库连接地址和密码等等。

但现在考虑到使用多环境打包,一般做法是将共同内容留在application.yml,不同内容放到不同配置环境中。

创建和前面 profile 命名一致的配置文件,比如这里创建

application-hengda.ymlapplication-xiaoju.yml ,里面自行填写个性化数据。

重点在 application.yml 中配置如下代码

spring:
  profiles:
    active: '@profileActive@'

导入对应配置文件

最后还需要在 pom.xml 中读取导入不同环境对应的配置文件,代码如下

<build>
		<!-- profile对资源的操作 -->
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>application*.yml</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<!-- 是否替换@xx@表示的maven properties属性值 -->
				<filtering>true</filtering>
				<includes>
					<include>application.yml</include>
					<include>application-${profileActive}.yml</include>
				</includes>
			</resource>
		</resources>
	</build>

Ok,搞定。

参考

spring boot 多环境配置

Maven Profile 与 Spring Profile 管理多环境打包

 

本文由老郭种树原创,转载请注明:https://guozh.net/spring-boot-profile-multi-environment-configuration-and-packaging/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注