使用场景:
maven打出的jar中pom.xml动态替换占位符
有些时候某些公共工具jar包被项目引用后发现公共jar的pom.xml中的version依然还是占位符,例如下面
java
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
如何让其打包后动态替换呢,即替换为最终的版本,像下面这样
java
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>>1.18.8</version>
</dependency>
打包后发现会在jar包中生成如果路径:target/classes/META-INF/maven/ g r o u p I d / {groupId}/ groupId/{artifactId}/pom.xml,经测试这个pom.xml才是最终生效的配置,那么如何替换呢。经过查找maven源码发现是硬编码到jar中的,源码如下
org.apache.maven.archiver.MavenArchiver#createArchive
所以我这边采取的是通过copy-resources重新替换解析后pom到META-INF/maven/ g r o u p I d / {groupId}/ groupId/{artifactId}/pom.xml,解决方法如下:
xml
<dependencies>
......
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<!--不要定义为default-resources,否则会覆盖maven默认的-->
<id>default-resources1</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<!--将当前项目下pom.xml解析替换占位符复制到目标文件中-->
<outputDirectory>target/classes/META-INF/maven/${groupId}/${artifactId}/</outputDirectory>
<overwrite>true</overwrite>
<resources>
<resource>
<directory>./</directory>
<includes>
<include>pom.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.5</version>
<configuration>
<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
另外maven如何错误的类不打入包内
因为依赖的环境不同,有些类可能会出现编译错误不想打入jar中,可以通过在profile中自定义插件排除,如下:在saas_prod打包时所有com/xxx/local 包下面的类将不会打入其中
xml
<profile>
<id>saas_prod</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<excludes>
<exclude>com/xxx/local/**/*.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</profile>
有问题随时私聊沟通,相互进步