1

您好下面是我的代码,它将用作连接工厂类。但我得到了 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)
4

1 回答 1

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因此nullConnFactory.

您需要颠倒这些静态字段声明的顺序:

public static final String DRIVER_CLASS = ...;
...
private static ConnFactory instance = new ConnFactory()

实际上,在我看来,最好完全摆脱这些静态字段。只需使它们非静态并在构造函数中初始化它们。

您还可以将 的实例传递Properties给构造函数,以将连接创建与连接属性的存储分离。如果这样做,您将能够在不同情况下使用不同的属性集(例如,用于测试和生产环境)。

于 2013-11-05T10:18:31.970 回答