我正在尝试通过存储在属性文件中的值来更改基本URL,从而使更改环境的过程更加简单,但是在触发测试时,URL的值似乎包含空值,而不是环境类型。
public class Global_Vars {
private static String testEnvironment;
static {
try{
Properties props = new Properties();
File file = new File(Global_Vars.CONFIG_PROPERTIES_DIRECTORY);
FileInputStream fileInput = new FileInputStream(file);
props.load(fileInput);
// process properties content
testEnvironment = props.getProperty("testEnvironment");
} catch (Exception ex) {
ex.getMessage();
}
}
//GLOBAL URL's
public static String HOMEPAGE_URL = "https://" + testEnvironment + ".deltaway.co.uk/";
我的属性文件包含以下值:
testEnvironment=test3
属性目录(Global_Vars.CONFIG_PROPERTIES_DIRECTORY)的位置也是正确的,有什么想法吗?
答案 0 :(得分:1)
似乎找不到属性文件。您可以通过打印异常来跟踪它(而不是ex.getMessage()->抛出异常或将其写入日志/控制台)。
请注意属性文件的位置。资源文件的推荐位置是:src / main / resources
以下代码(基于您的代码)将解决问题:
package main;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class PopertiesFileSeemsToBeProducingANullPointerException {
private static String testEnvironment;
private static final String CONFIG_PROPERTIES_DIRECTORY = "src/main/resources/envs.properties";
//GLOBAL URL's
public static String HOMEPAGE_URL = "https://" + testEnvironment + ".deltaway.co.uk/";
static {
try{
Properties props = new Properties();
File file = new File(PopertiesFileSeemsToBeProducingANullPointerException.CONFIG_PROPERTIES_DIRECTORY);
FileInputStream fileInput = new FileInputStream(file);
props.load(fileInput);
// process properties content
testEnvironment = props.getProperty("testEnvironment");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
System.out.println(testEnvironment);
}
}
但是我不建议您使用此代码,因为它存在一些问题:
更好的实现是添加接口Iconfig 和实现该接口的Config类
我建议通过以下方式解决问题:
IConfig接口:
public interface IConfig {
public void init();
}
Config类:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import lombok.Data;
@Data
public class Config implements IConfig{
private final String PROPERTIES_FILE = "envs.properties";
private final String ENVIRONMENT = "testEnvironment";
private String env;
public void init(){
try(InputStream is = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)){
Properties props = new Properties();
props.load(is);
env = props.getProperty(ENVIRONMENT);
} catch (IOException e) {
throw new RuntimeException("Failed to read properties file due to IO issues");
}
}
}
在驱动程序中加载配置:
@Autowired
IConfig config;
private void loadConfig() {
config.init();
}
您可以打印所需的信封:
System.out.println(config.getEnv());