这是我pom.xml的一部分,具有两个配置文件,其中包含指向不同环境的URL:
<profiles>
<profile>
<id>test</id>
<properties>
<environment>yyy</environment>
</properties>
</profile>
<profile>
<id>uat</id>
<properties>
<environment>xxx</environment>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
我在evironment.properties
中还有src/main/java/resources
个文件,正文:
environment=${environment}
我使用mvn clean test -Ptest运行程序 现在如何从Maven个人资料中获取价值? 我创建了阅读器类:
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Reader {
public void readProperties() {
Reader app = new Reader();
Properties prop = app.loadPropertiesFile("src\\test\\resources\\properties\\environment.properties");
prop.forEach((k, v) -> System.out.println(k + ":" + v));
}
public Properties loadPropertiesFile(String filePath) {
Properties prop = new Properties();
try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(filePath)) {
prop.load(resourceAsStream);
} catch (IOException e) {
System.err.println("Unable to load properties file : " + filePath);
}
return prop;
}
}
但是如果我在测试中运行读取器功能,它将在以下位置提供NullPointer:
Reader objReader = new Reader();
objReader.readProperties();
如何访问个人资料中定义的URL?
答案 0 :(得分:0)
您应将以下内容放入您 pom.xml :
构建部分:
<build>
<resources>
<resource>
<directory>src/main/resources/${custom.resource}</directory>
<filtering>true</filtering>
</resource>
</resources>
....
<profiles>
<profile>
<id>cloud</id>
<properties>
<custom.resource>devnew</custom.resource>
</properties>
</profile>
...
devnew 配置本身可能类似于:https://i.imgur.com/gHR5BTk.png
baseUrl=abracadabra....
您的道具装载者将看起来:
public void environmentPropertiesLoader() throws IOException {
Properties prop = new Properties();
String propFileName = "custom.resource";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream == null) {
throw new FileNotFoundException("Property File '" + propFileName + "' not found in the classpath");
}
prop.load(inputStream);
baseUrl = prop.getProperty("baseUrl");
inputStream.close();
}
您使用配置文件的正确命令将显示为:
mvn clean test "-Pdevnew
“
希望这对您有帮助。
还推荐the article describing how to set up maven project from scratch。
最好的问候, 尤金