【发布时间】:2020-11-05 19:09:39
【问题描述】:
我在一个 java 常量中有一个文本,我想根据一个在生成工件时配置的 maven 变量来替换它:
public class FOO {
public static final String BASE = "/@FOO@";
}
问题是如果我替换java代码,它会被永远替换并且不再执行替换,所以如果我更改变量的值它没有效果:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>${basedir}/src/main/java/com/my/package/Constants.java</include>
</includes>
<replacements>
<replacement>
<token>@FOO@</token>
<value>${my.custom.property}</value>
</replacement>
</replacements>
</configuration>
</plugin>
我已经通过相反的过程解决了这个问题:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<id>first-execution</id>
<phase>generate-sources</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<includes>
<include>${basedir}/src/main/java/com/my/package/Constants.java</include>
</includes>
<replacements>
<replacement>
<token>@FOO@</token>
<value>${my.custom.property}</value>
</replacement>
</replacements>
</configuration>
</execution>
<execution>
<id>second-execution</id>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<includes>
<include>${basedir}/src/main/java/com/my/package/Constants.java</include>
</includes>
<replacements>
<replacement>
<token>${my.custom.property}</token>
<value>@FOO@</value>
</replacement>
</replacements>
</configuration>
</execution>
</executions>
</plugin>
但是这第二步可能很危险,因为可能会发生冲突并替换类的 java 代码中具有相同值的内容。
另一种选择是在 .class 文件中替换如下:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>${basedir}/target/my-artifact-directory/WEB-INF/classes/com/my/package//Constants$PATHS.class</include>
</includes>
<replacements>
<replacement>
<token>@FOO@</token>
<value>${my.custom.property}</value>
</replacement>
</replacements>
</configuration>
</plugin>
替换有效,但应用程序未正确启动。 关于如何在不修改原始代码的情况下执行替换的任何其他想法?
【问题讨论】:
-
我建议深入研究mojohaus.org/templating-maven-plugin,它比替换器等要好得多,尤其是与 Java 源代码的关系...
-
此外,在资源中拥有一个属性文件并在 Java 程序中读取该文件可能就足够了。
-
我认为关键不是原地替换而是复制到生成的源并保持原始不变,如模板-maven-plugin的示例
-
设置应该是运行时属性吗?那将是一种更简单、更现代的方法。
标签: java maven maven-replacer-plugin