gpt4 book ai didi

java - 使用maven构建带有参数的java项目

转载 作者:太空宇宙 更新时间:2023-11-04 10:11:03 25 4
gpt4 key购买 nike

我想使用带有参数的 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();
}
}
}

我的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>

error shown in eclipse

     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

关于java - 使用maven构建带有参数的java项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52316154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com