我创建了两个 Maven 配置文件。一种用于开发,一种用于质量保证。
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<cofiguration.path>src/test/resources</cofiguration.path>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<systemPropertyVariables>
<appEnv>dev</appEnv>
<userFile>application.properties</userFile>
<Selenium_Broswer>chrome</Selenium_Broswer>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>qa</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<systemPropertyVariables>
<appEnv>qa</appEnv>
<userFile>application.properties</userFile>
<Selenium_Broswer>firefox</Selenium_Broswer>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
还有一个类来读取属性
public class PropertyFile {
private static Properties prop;
private static void getPropertyFile() {
String appFilePath = System.getProperty("user.dir") + "/src/test/resources/" + System.getProperty("appEnv") + ".properties";
try (InputStream in = new FileInputStream(appFilePath)) {
prop = new Properties();
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String propertyName) {
if (prop == null) {
getPropertyFile();
}
return prop.getProperty(propertyName);
}
}
基本上,我想要做的是当我运行 mvn test -Pdev 时。它将获取maven配置文件“appEnv”中的变量
例如,当 mvn test -Pdev 时,appEnv 为 dev。在PropertyFile类中,它将获取appEnv并找到正确的属性文件(我在资源文件夹下有dev.properties和qa.properties,文件中有一些基本url和其他属性)
但是现在,当我调用 PropertyFile.getProperty("baseUrl")
时,它会返回 NPE。问题是什么?我应该如何更改代码和maven配置文件?
最佳答案
只需修复你的 NPE:
私有(private)静态属性 prop=new Properties();
和
if (prop.isEmpty()) {
getPropertyFile();
}
<小时/>
请使用Resources.getResource(path)
获取资源文件。
如果是 Spring 项目,最好在应用程序文件中添加不同的配置文件,然后添加属性 bean 来加载值。
关于java - 使用 Maven 配置文件加载正确的属性文件时获取 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368308/