我想使用带参数的Maven构建一个Java项目,这些参数在每次构建时都会发生变化。一个参数是例如在程序内部检查的密钥。
一旦项目构建完成,这些参数应该不能被读出。尝试了不同的方法,包括来自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();
}
}
}
我的pom.xml
<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)
发布于 2018-09-14 03:56:47
我猜你在搜索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
https://stackoverflow.com/questions/52316154
复制相似问题