【发布时间】:2019-12-13 13:12:59
【问题描述】:
我创建了两个 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 配置文件?
【问题讨论】:
-
1.
src目录在运行时不存在,因此您必须查找文件,可能在运行时将出现的资源目录中。 2. 资源不是文件。您应该在这里使用getResourceAsStream(),并在空值检查方面做得更好。
标签: java maven properties-file maven-profiles