经过一些研究,我的解决方案如下所示,
对于给定的参数“test”:
目标 1.: 执行 maven 构建时使用命令行参数,例如使用:
install -Dtest=OnBuildValue
然后使用 maven 资源插件,它通过构建时的给定参数替换属性文件中的 test=${test} 等字符串。添加:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven.resources.version}</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
...
<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/parameters.properties</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
....
</build>
到目标2:为了能够改变容器中的参数“test”,而不必重建war文件,添加一个JVM参数-DTEST=ContainerValue。
现在我们需要一些逻辑:
private static String getBuildParameter(String paramName)
throws IOException {
Resource resource = new ClassPathResource(
"/META-INF/spring/parameters.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
return props.getProperty(paramName);
}
public static String getParameter(final String paramName,
final String defaultValue, final String logMessage) {
String value = System.getProperty(paramName);
if (value!=null) {
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + value
+ " found in JVM parameters.");
return value;
}
try {
value = getBuildParameter(paramName.toLowerCase());
} catch (IOException e) {
// catch, log exception...
}
if (value!=null) {
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + value
+ " found in parameters set on build time.");
return value;
}
Logger.getLogger(ParameterManager.class.getName()).log(
Level.WARNING,
"Parameter: " + paramName + ": " + defaultValue
+ " as default parameter. " + logMessage);
return defaultValue;
}
这些方法是静态的,因为我使用它们来初始化常量,如下所示:
public static final String TEST_STRING;
static {
TEST_STRING = getParameter("TEST", "default value",
"The default is set, please ensure, that this is intended!");
}
然后可以从项目中的任何地方读取这些常量。你如何称呼这个逻辑,或者你是否可以用不同的方式实现它取决于你。我确信有更好的方法,我很高兴听到你的实现,但这对我有用。
注意 1.:
如果您使用 Eclipse,您可以在 Run->Run configurations->Goals 下定义 maven 参数。
但是如果您使用 glassfish 工具(m2e 插件)将项目部署到 glassfish,它将不会使用运行配置。然后您必须创建文件 .m2/settings.xml,如下所示:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd>
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies/>
<profiles>
<profile>
<id>m2e</id>
<activation>
<property>
<name>m2e.version</name>
</property>
</activation>
<properties>
<test>xmlparameter</test>
</properties>
</profile>
</profiles>
<activeProfiles/>
</settings>