前言
有時 Maven 項目中構建完后還需要做一些較復雜的文件操作,這時我們可以考慮使用 maven-antrun-plugin 插件在 Maven 的 pom 中配置調用 Ant 任務。
格式:
<build>
<plugins>
<!--
...
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<!-- 執行打包操作時執行的任務 -->
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo> 執行一些 Ant 任務:</echo>
<echo file="${basedir}/target/port.txt">${server.port}</echo>
<mkdir dir="xxx"/>
<copy file="test.properties" todir="xxx" overwrite="true" />
<copydir src="../xxx" dest="../yyy" />
<copy todir="../xxx" overwrite="true" >
<fileset dir="../xxx" />
</copy>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
tasks 標簽下的內容就是具體 Ant 執行的任務了。
更多可執行的任務標簽可參考:http://ant.apache.org/manual/tasksoverview.html
使用實例1:
<build>
<plugins>
......
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<!-- 復制newrelic-agent.jar包到指定目錄(target/)下 -->
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeArtifactIds>newrelic-agent</includeArtifactIds>
<outputDirectory>${project.build.directory}</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>id.package</id>
<!-- 執行打包操作時執行的任務 -->
<phase>package</phase>
<configuration>
<target>
<!-- 把 ${basedir}\*.sh 文件復制到 ${basedir}\target 目錄下 -->
<copy todir="${basedir}/target" overwrite="true">
<fileset dir="${basedir}">
<include name="*.sh"/>
</fileset>
</copy>
<!-- 給 target/*.sh 授權 -->
<chmod file="target/*.sh" perm="755"/>
<!-- 替換指定文件中的8080為${server.port} -->
<replace file="target/stop-${project.artifactId}.sh" token="8080" value="${server.port}"></replace>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<!-- 將應用中默認的newrelic.yml配置文件,復制到指定目錄(target/)下 -->
<id>id.newrelic</id>
<phase>package</phase>
<configuration>
<target>
<copy todir="${basedir}/target/">
<fileset dir="${basedir}/src/main/resources/conf_${spring.profiles.active}">
<include name="newrelic.yml"/>
</fileset>
</copy>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
使用實例2:
<build>
<plugins>
......
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- 解壓newrelic-agent.jar中包含的所有文件 到 應用的jar包中 -->
<id>addExtractedJarOnRootLevel</id>
<phase>package</phase>
<configuration>
<target>
<zip destfile="${project.build.directory}/${project.artifactId}.jar" update="yes" compress="false">
<zipfileset src="${com.newrelic.agent.java:newrelic-agent:jar}" />
</zip>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
