如何在Maven编译前替换代码中的字符串占位符?
解决Kotlin代码中Maven版本占位符替换问题
你遇到的核心问题是插件执行阶段太晚(prepare-package在编译之后),且直接修改了原始源码,导致替换后的内容未被编译。下面提供两种不修改原始源码、仅在编译阶段完成占位符替换的方案:
方案一:使用maven-replacer-plugin处理源码副本
通过将源码复制到临时目录并完成替换,再让编译器编译这个修改后的副本,原始源码完全不受影响。
1. 配置replacer插件,输出到临时目录
修改插件配置,指定输出目录为target下的临时源码文件夹,并将执行阶段调整到编译前的process-sources:
<plugin> <groupId>com.google.code.maven-replacer-plugin</groupId> <artifactId>replacer</artifactId> <version>1.5.1</version> <executions> <execution> <phase>process-sources</phase> <!-- 编译前执行替换 --> <goals> <goal>replace</goal> </goals> </execution> </executions> <configuration> <file>src/main/kotlin/tech/goksi/pterobot/util/VersionCheck.kt</file> <outputFile>target/generated-sources/kotlin/tech/goksi/pterobot/util/VersionCheck.kt</outputFile> <replacements> <replacement> <token>@VERSION@</token> <value>${project.version}</value> </replacement> </replacements> </configuration> </plugin>
2. 将临时目录添加为编译源
使用build-helper-maven-plugin把临时目录加入编译源列表,确保编译器处理替换后的代码:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>target/generated-sources/kotlin</source> </sources> </configuration> </execution> </executions> </plugin>
方案二:使用Maven资源插件过滤源码
利用Maven自带的资源插件完成占位符过滤,无需额外引入replacer插件。
1. 配置资源插件复制并过滤源码
<plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.3.1</version> <executions> <execution> <id>copy-and-filter-sources</id> <phase>process-sources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>target/generated-sources/kotlin</outputDirectory> <resources> <resource> <directory>src/main/kotlin</directory> <filtering>true</filtering> <includes> <include>tech/goksi/pterobot/util/VersionCheck.kt</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin>
2. 修改Maven占位符分隔符
由于你的占位符是@VERSION@格式,需要在pom.xml的properties中修改资源过滤的分隔符:
<properties> <maven.resources.delimiters>@</maven.resources.delimiters> <maven.resources.escapeString>\</maven.resources.escapeString> </properties>
3. 添加临时目录为编译源
同样使用build-helper-maven-plugin将target/generated-sources/kotlin加入编译源,配置同方案一的第二步。
两种方案都会在编译前完成占位符替换,且仅修改target目录下的临时文件,原始源码保持干净,最终编译打包的代码会包含正确的版本号。
内容的提问来源于stack exchange,提问作者Вукашин Лекић
相关产品推荐
相关产品推荐

