maven使用build resources标签和profiles标签指定打包资源和发布环境
项目开发中,开发环境和生产环境所用到的某些配置肯定是不同的,因此我们往往在项目中会使用两套资源配置,比如在resources目录下分别建立dev/jdbc.properties和pro/jdbc.properties,那么问题来了,怎么在打包发布的时候根据环境不同指定要打包哪个环境下的资源文件呢?这时就要用到maven下的build resources标签和profiles标签了,俩个标签相互配合来达到此目的。
dev和pro两个文件夹下分别有两个jdbc.properties资源文件,内容分别为jdbc=dev和jdbc=pro。maven的pom下配置profiles标签并指定pro下的资源文件为默认环境,resources下排除dev和pro环境下的资源文件,标签里的资源文件将不被maven打包编译,然后作以下配置:
<resource>
<!-- 配合profiles标签可以让被激活环境下的资源配置全部编译到classpath下 -->
<directory>src/main/resources/${env}</directory>
</resource>
可将指定被激活的jdbc.properties直接编译到classpath下:
打开编译好的jdbc.properties:
发现是我们需要的环境配置,大功告成!
此外,实际项目开发中,默认激活的配置一般都为dev环境,pom文件上传到生产环境后,就暂时解除git关联,以后本地开发就用默认环境配置即可。生产环境下更改pom中的默认配置,调整为pro,一直用这套来进行项目的编译打包即可。如果本地pom中的依赖有变化,生产环境下的pom一般要手动把增加的依赖给添上,然后在编译打包。为什么要手动?为了避免本地开发时,团队成员误操作导致生产环境错误地引用资源(实际上在团队进行开发时,有人可能不清楚profiles是干嘛用的,仅仅增加了依赖就推到了生产环境,就导致生产环境默认激活了开发所用的dev资源,然后…等着背锅吧骚年~),所以手动更新pom虽然麻烦但却是最安全的一种方式。
pom.xml下的具体代码如下:
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<!-- 发布环境 -->
<id>pro</id>
<properties>
<env>pro</env>
</properties>
<activation>
<!-- 设置默认激活这个配置 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.txt</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.txt</include>
</includes>
<excludes>
<exclude>dev/*</exclude>
<exclude>pro/*</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<!-- 配合profiles标签可以让被激活环境下的资源配置全部编译到classpath下 -->
<directory>src/main/resources/${env}</directory>
</resource>
</resources>
</build>