我需要编写一个连接到数据库的Web应用程序,并从.properties文件中读取连接属性。
我使用Maven,我想为我的应用程序编写一些单元测试。
要测试使用数据库的类,我将.properties文件放到src / main / resources并测试/ main / resources并编写以下代码来读取属性:
package util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
*
* @author proger
*/
public class ProgrammSettings {
private static Logger logger = Logger.getRootLogger();
private static String propertiesPath = "program.settings.properties";
private static Properties props;
public static String getProperty(String key) {
if (props == null)
loadProperties();
return props.getProperty(key);
}
public static void setResourcesFilePath(String path) {
propertiesPath = path;
}
private static void loadProperties() {
InputStream propOut = null;
try {
//URL url = ClassLoader.getSystemResource(propertiesPath);
propOut = ClassLoader.getSystemClassLoader().getResourceAsStream(propertiesPath); //new FileInputStream(url.getFile());
props = new Properties();
props.load(propOut);
} catch (Exception ex) {
//Logger.getLogger(ProgrammSettings.class.getName()).log(Level.SEVERE, null, ex);
String errorMessage = "Error during properties file reading. Path to file: '" +
propertiesPath + "'";
logger.error(errorMessage, ex);
throw new RuntimeException(errorMessage, ex);
} finally {
try {
if (propOut != null)
propOut.close();
} catch (IOException ex) {
logger.error("Error during closing stream from properties file", ex);
}
}
}
}
我希望相同的代码同时适用于测试和应用程序类,因此我从classPath读取属性文件。 我的所有测试都通过了,我的.properties文件被Maven包装成了战争。但是当我从Netbeans运行我的应用程序时,我收到:
java.lang.NullPointerException
java.util.Properties$LineReader.readLine(Properties.java:435)
java.util.Properties.load0(Properties.java:354)
java.util.Properties.load(Properties.java:342)
util.ProgrammSettings.loadProperties(ProgrammSettings.java:49)
util.ProgrammSettings.getProperty(ProgrammSettings.java:33)
dataacess.AbstractDataMapper.loadDriver(AbstractDataMapper.java:58)
dataacess.AbstractDataMapper.<init>(AbstractDataMapper.java:41)
dataacess.UserMapper.<init>(UserMapper.java:25)
servlets.UserRegistration.processRequest(UserRegistration.java:86)
servlets.UserRegistration.doPost(UserRegistration.java:132)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
我该如何解决?提前谢谢
答案 0 :(得分:3)
将program.settings.properties
放在webapps/appname/WEB-INF/classes
你可以使用更简单的行ProgrammSettings.class.getResourceAsStream(..)
(即不是系统类加载器,但是当前的类加载器)