嗨下面是我的代码,它将用作Connection Factory类。但我得到java.lang.ExceptionInInitializerError。请指教如何解决?我认为这是陷阱,因为静态阻塞,但不知道究竟是什么。
package j2ee.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class ConnFactory
{
public static Properties prop;
static
{
prop=new Properties();
try {
prop.load(ConnFactory.class.getClassLoader().getResourceAsStream("DBConfig.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
private static ConnFactory instance = new ConnFactory();
public static final String URL = prop.getProperty("DEVURL");
public static final String USER = prop.getProperty("DEVUSER");
public static final String PASSWORD = prop.getProperty("DEVPASSWORD");
public static final String DRIVER_CLASS = prop.getProperty("DEVDRIVER_CLASS");
private ConnFactory() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("ERROR: Unable to Connect to Database.");
}
return connection;
}
public static Connection getConnection() {
return instance.createConnection();
}
public static void main(String a[])
{
Connection test=ConnFactory.getConnection();
System.out.println("Done");
}
}
错误是:
Caused by: java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at j2ee.dao.ConnFactory.<init>(ConnFactory.java:28)
at j2ee.dao.ConnFactory.<clinit>(ConnFactory.java:20)
答案 0 :(得分:1)
private static ConnFactory instance = new ConnFactory(); // DRIVER_CLASS is null at this point
...
public static final String DRIVER_CLASS = ...;
在初始化ConnFactory
之前创建DRIVER_CLASS
的实例,因此DRIVER_CLASS
的构造函数中null
为ConnFactory
。
您需要颠倒这些静态字段声明的顺序:
public static final String DRIVER_CLASS = ...;
...
private static ConnFactory instance = new ConnFactory()
实际上,在我看来,最好摆脱这些静态字段。只需使它们非静态并在构造函数中初始化它们。
您还可以将Properties
的实例传递给constuctor,以将连接创建与连接属性的存储分离。如果这样做,您将能够在不同情况下使用不同的属性集(例如,对于测试和生产环境)。