因为您的 Java 文件将在您有机会更改变量之前被编译,所以您尝试的普通过滤器将不起作用。但是,我能够使用 maven-replacer-plugin 实现类似的效果,它只是替换文件中的字符串。对我来说,像您建议的那样进行设置要干净得多,其中${my_variable} 格式的变量可以始终替换为某个当前版本。
但是,使用 maven-replacer-plugin 并没有那么奢侈,因为它实际上是在修改原始源文件本身。因此,如果您告诉它在某个时间点用${my_variable} 替换Version 1.2.3,文件将不再包含文本"${my_variable}",因为它已经被替换了。所以你必须重新考虑你的替代策略。这是我设置的...
我添加了一个名为“VersionManager”的共享类,它只有以下代码:
public class VersionManager {
private static String version="empty";
public static String getVersion(){
return version;
}
}
在<project><properties> 中,我添加了以下行(可选):
<display_version>v${project.version} #${BUILD_ID}</display_version>
然后包含 maven-replacer-plugin 并配置如下:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.0</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<file>--yourDirectoryPaths--/shared/VersionManager.java</file>
<replacements>
<replacement>
<token>private static String version=\".*\";</token>
<value>private static String version="${display_version}";</value>
</replacement>
</replacements>
</configuration>
</plugin>
如您所见,我告诉插件将包含 private static String version="*"; 的行替换为新行,其中包含大部分相同的文本,但引号内包含所需的版本号。
您可以通过运行 mvn validate 来测试它而无需编译整个项目,这将运行替换并且应该出现在您的源文件中。
那么你的服务器和客户端都知道它们在构建时运行的是什么版本。