通过maven profile 打包指定环境配置(excludes去除无用包)通过配置pom实现打包时根据不同环境选择对应的配置文件

1.背景:在发布项目时经常有不同环境不同配置的情况,每次都更改,造成重复工作,所以通过配置maven的pom文件来实现把不同环境的配置文件打包到指定文件下

2.废话不多说,上代码,下面是我目前的配置文件存放的位置,目前存放与config文件夹下,并创建了3个目录来存放不同的环境的配置文件,如下图

3.最终想实现的效果是通过打包命令把对应的环境的配置文件打包到class目录(这样springboot项目启动后就可以直接访问到配置文件),下面是最终的效果
 

4.首先需要配置pom文件 ,在pom文件中增加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>pro</id>
			<properties>
				<profiles.active>pro</profiles.active>
			</properties>
		</profile>
	</profiles>

5.配置build节点,如下(起作用的主要是resources节点内容)
 

<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>
		</plugins>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
				<excludes>
					<exclude>config/**</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources/config/${profiles.active}</directory>
				<!--targetPath是指定目标文件打包到哪个文件夹下,这里默认就是放到resources下,也就是打包后的class文件夹下-->
				<!--<targetPath>config</targetPath>-->
			</resource>
		</resources>
	</build>

6.这里先普及一下上面的各个节点的作用

(1)targetpath 是指定build资源到哪个目录 默认的话是class目录

  (2)${profiles.active}这个是动态的参数,也就是我们在第4步中对应的dev,test,pro变量

  (3)directory 是指定属性文件的目录,扫描将其放入到targetpath目录下,默认的话是        ${basedir}/src/main/resourses

  (4)includes 包含指定文件的扫描

  (5)excludes 指定文件不包含

  (6)filtering 是否将filter文件 (即里面的properties文件)的变量值在resourses中变为有效
7.使用打包命令进行打包

## 开发环境打包
mvn clean package -P dev

## 测试环境打包
mvn clean package -P test

## 生产环境打包
mvn clean package -P pro

8,如果使用的是ide,也提供了页面直接操作,如下图,选择了指定环境配置就可以打包制定文件

猜你喜欢

转载自blog.csdn.net/fengbaozonghuiguoqu/article/details/123366228