对于maven而言,打包是其一个非常重要的功能,不仅仅是简单的编译打包的概念,其还通过各种插件支持各种灵活的打包策略。现举一个例子讲解如何动态实现一个web项目的打包:
需求:
现需要对一个web项目打出不同的3个包,3个包除了有公共的jar和配置文件依赖外,还各自需要依赖不同的特定的jar和特定的配置文件,而且不同的war包名字最好是不同的。
实现:
我们可以利用 maven的profile机制和maven-war-plugin插件来完成以上需求,所有需要配置和修改的只涉及项目的pom文件,首先我们在pom文件中加入profile,不同的profile引入特定的jar依赖和动态定义${env}变量
<profiles>
<profile>
<id>one</id>
<properties>
<env>one</env>
</properties>
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>project-one</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>two</id>
<properties>
<env>two</env>
</properties>
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>project-two</artifactId>
</dependency>
</dependencies>
</profile>
<profile>
<id>three</id>
<properties>
<env>three</env>
</properties>
<dependencies>
<dependency>
<groupId>com.xxx</groupId>
<artifactId>project-three</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
然后引入maven-war-plugin插件,实现打包时根据不同的${env}变量动态引入不同的资源文件,并动态设定打包的包名:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<webResources>
<resource>
<directory>deploy/${env}</directory>
<targetPath>WEB-INF/classes</targetPath>
<filtering>true</filtering>
</resource>
</webResources>
<warName>project-${env}</warName>
</configuration>
</plugin>
然后在项目下使用 mvn clean install -Dmavent.test.skip=true -P ${profile_id} 进行打包 ,${profile_id}指各个不同的profile的id