我有以下类从属性文件加载数据库详细信息。当文件“dao.properties”丢失时,该类应该抛出DAOConfigurationException但是我得到了
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.ExceptionInInitializerError
com.clone.dao.DAOFactory.getInstance(DAOFactory.java:19)
com.clone.controller.register.doPost(register.java:35)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
com.clone.dao.DAOConfigurationException: Properties file dao.properties not found in classpath.
com.clone.dao.DAOProperties.<clinit>(DAOProperties.java:15)
com.clone.dao.DAOFactory.getInstance(DAOFactory.java:19)
com.clone.controller.register.doPost(register.java:35)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
并且在随后的请求中我得到了这个例外
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: Could not initialize class com.clone.dao.DAOProperties
com.clone.dao.DAOFactory.getInstance(DAOFactory.java:19)
com.clone.controller.register.doPost(register.java:35)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
这是我的代码
package com.clone.dao;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class DAOProperties {
private static final String PROPERTIES_FILE = "dao.properties";
private static final Properties PROPERTIES = new Properties();
<b> static{
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream propertiesFile = classloader.getResourceAsStream(PROPERTIES_FILE);
if(propertiesFile==null){
throw new DAOConfigurationException("Properties file "+PROPERTIES_FILE+" not found in classpath.");
}
try {
PROPERTIES.load(propertiesFile);
} catch (IOException e) {
throw new DAOConfigurationException("Cannot load properties file '"+PROPERTIES_FILE+"'.", e);
}
}
</b>
private String specificKey;
public DAOProperties(String specificKey)
{
this.specificKey=specificKey;
}
public String getProperty(String key) throws DAOConfigurationException {
String fullKey = specificKey+"."+key;
String property = PROPERTIES.getProperty(fullKey);
if(property==null||property.trim().length()==0){
throw new DAOConfigurationException("Property '"+fullKey+"' is missing in properties file '"+
PROPERTIES_FILE+"'.");
}
return property;
}
}
伙计们,请解释发生的事情,这很麻烦
答案 0 :(得分:3)
投掷DAOConfigurationException
:
com.clone.dao.DAOConfigurationException: Properties file dao.properties
not found in classpath.
但是,由于java.lang.ExceptionInInitializerError
正在尝试使用DAOFactory
,因此DAOProperties
已完全包含在内。 DAOProperties
类无法正确初始化,因为静态初始化程序失败,而ExceptionInInitializerError
正是静态初始化程序失败时抛出的内容。
也许您不应该在静态初始化程序中执行此操作?