在使用springboot时,很简单,通过@Value注解就能轻易拿到配置信息,就像这样:
report.path = D:\\js\\phantomjs-2.1.1-windows\\bin\\report\\
exe.path = D:\\js\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe
js.path = D:\\js\\phantomjs-2.1.1-windows\\bin\\rxLevRxQual.js
chartJS.path = D:\\js\\phantomjs-2.1.1-windows\\bin\\chart.js
@Value("${report.path}")
private String reportPath;
@Value("${exe.path}")
private String exePath;
@Value("${js.path}")
private String jsPath;
但是如果不使用springboot,就简单的spring项目,那就得这样取了:
public class C3reportController {
public static Properties properties;
static{
try {
properties = new Properties();
//File propertiesFile = new File("interfaceMonitoringWebApp/src/main/resourcese/config/conf.properties");
//InputStreamReader propertiesReader = new InputStreamReader(new FileInputStream(propertiesFile.getAbsolutePath()), "UTF-8");
// 定义 Properties 对象 properties
// 通过 Properties 类的 load 方法来读取 properties 文件中的变量
InputStream in = C3reportController.class.getClassLoader().getResourceAsStream("config/config.properties");
properties.load(in);
in.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注释掉的代码是通过绝对路径去读取的,放开的这种是通过相对路径去取的,
拿到Properties对象之后,通过取键值对的方式取配置信息就好了:
String reportPath = properties.getProperty("reportPath");