Maven插件-打包时多环境配置文件设置

xiaoxiao2021-02-28  14

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

<!-- java代码路径 --> <sourceDirectory>src/main/java</sourceDirectory> <!-- test代码路径 --> <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> <!-- 资源文件不包含web.xml --> <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> <!-- 使用web.xml文件路径 --> <webXml>src/wfconfig/${env}/web.xml</webXml> <!-- 将某些需要的文件拷贝到WEB-INF下 --> <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插件-打包时多环境配置文件设置

转载请注明原文地址: https://www.6miu.com/read-200139.html

最新回复(0)