[英]Get NPE when loading correct properties file with Maven profile
我创建了两个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并找到正确的属性文件(我在resources文件夹下有dev.properties和qa.properties,并且文件中有一些基本url和其他属性)
但是现在,当我调用PropertyFile.getProperty("baseUrl")
时,它将返回NPE。 问题是什么? 我应该如何更改代码和Maven个人资料?
只需修复您的NPE:
private static Properties prop=new Properties();
和
if (prop.isEmpty()) {
getPropertyFile();
}
请使用Resources.getResource(path)
获取资源文件。 如果是Spring项目,这是在应用程序文件中添加其他概要文件然后添加属性Bean来加载值的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.