Maven插件-打包时多环境配置文件设置
同一个项目,测试、生产环境配置内容是不同的,如何通过Maven插件在不同的环境下使用不同的配置文件呢?
项目结构
Profile
定义一些列配置信息,然后通过命令激活指定信息,一般在项目pom.xml文件中配置。
<profiles>
<profile>
<id>dev
</id>
<properties>
<env>dev
</env>
</properties>
<activation>
<activeByDefault>true
</activeByDefault>
</activation>
</profile>
<profile>
<id>qa
</id>
<properties>
<env>qa
</env>
</properties>
</profile>
<profile>
<id>prd
</id>
<properties>
<env>prd
</env>
</properties>
</profile>
</profiles>
mvn打包命令:
mvn clean
package -Pdev/qa/prd
build中resource
<sourceDirectory>src/main/java
</sourceDirectory>
<testSourceDirectory>src/test/java
</testSourceDirectory>
<testResources>
<testResource>
<directory>src/test/resources
</directory>
</testResource>
</testResources>
<resources>
<resource>
<directory>src/main/resources
</directory>
</resource>
<resource>
<directory>src/wfconfig/${env}
</directory>
<excludes>
<exclude>*.xml
</exclude>
</excludes>
</resource>
</resources>
通过配置resouces,我们就可以通过mvn clean package -Pqa指定不同环境下的配置文件,但是该方法仅仅可以把配置文件加载到webapp/classes文件夹下,无法替换webapp/WEB-INF/web.xml文件。
maven-war-plugin插件
<plugins>
<plugin>
<groupId>org.apache.maven.plugins
</groupId>
<artifactId>maven-war-plugin
</artifactId>
<version>2.6
</version>
<configuration>
<failOnMissingWebXml>false
</failOnMissingWebXml>
<webXml>src/wfconfig/${env}/web.xml
</webXml>
<webResources>
<resource>
<directory>src/wfconfig/${env}
</directory>
<targetPath>WEB-INF
</targetPath>
<includes>
<include>**/*.xml
</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
配置后在打包时即可按照-P参数从指定配置文件中拉去web.xml文件,maven-war-plugin更多操作参见(https://maven.apache.org/plugins/maven-war-plugin/war-mojo.html)。
完整示例
https://github.com/Wang-Jun-Chao/JavaEE_And_SpringBoot/tree/54322bd8d56f4b92ce2886aea9671f5a1c6cdbbe/002-Maven插件-打包时多环境配置文件设置