我想使用带有参数的Maven构建一个Java项目,这些参数在每个构建中都会发生变化。一个参数例如是在程序内部检查的键。
一旦构建项目,就不应该读出参数。试过不同的Approche,包括来自org.codehaus.mojo的插件......但是有“插件执行未被生命周期覆盖”的问题....
/****************************/
/**read property values */
/****************************/
//Create a new property list
Properties properties = new Properties();
//create a input strem
InputStream inputStream = null;
//try to read the property file
try {
String filename ="restApi.properties";
inputStream = Main.class.getClassLoader().getResourceAsStream(filename);
if(inputStream==null) {
System.out.println("Unable to read required properties");
}
properties.load(inputStream);
System.out.println(properties.getProperty("property_mainUrlValue"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我们认为
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<property_mainUrlValue>property_mainUrlValue</property_mainUrlValue>
<properties>
<build>
<sourceDirectory>src</sourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-2</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}/restApi.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
Unable to read required properties
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at itAsset.Main.main(Main.java:58)
我想你正在寻找Maven所谓的(由于某些我不理解的原因)“过滤”。
基本的想法是这样的:
您可以通过在pom.xml
中包含以下配置来启用该功能:
...
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
...
这导致当你运行mvn resources:resources -Dkey="mmm123"
,并且你有一个包含行的资源src/main/resources/restApi.properties
appKey=${key}
然后Maven将在target/classes/restApi.properties
中创建一个包含的资源输出
appKey=mmm123
详细说明如下:http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html