Class.forName(classPath).newInstance() 时也要注意此问题的产生
错误代码:
private String getDb() {
Properties pro = new Properties();
String resourcePath = "config.properties";
try {
pro.load(
this.getClass().
getClassLoader().
getResourceAsStream(resourcePath)
);
db = pro.getProperty("db");
} catch (IOException e) {
e.printStackTrace();
}
return db;
}
问题:db为null
分析:java程序默认是在根路径 src下查找,所以要指定路径
解决:
private String getDb() {
Properties pro = new Properties();
String resourcePath = "com/bigtalk/patterns/abstractFactory/config.properties";
try {
pro.load(
this.getClass().
getClassLoader().
getResourceAsStream(resourcePath)
);
db = pro.getProperty("db");
} catch (IOException e) {
e.printStackTrace();
}
return db;
}