日期:2014-05-16  浏览次数:20457 次

一个关于数据库实现类初使化的解决办法

前几天写了个数据库链接池类,但有个问题使终解决得不太满意,所以贴出来让大家帮我想想办法啦.....
首先写了个ConnectionFactory接口类,代码如下:

package com.luoyu.persistence;

public interface ConnectionFactory {
public static final String CONNECTION_USERNAME = "connection.username";

public static final String CONNECTION_PASSWORD = "connection.password";

public static final String CONNECTION_URL = "connection.url";

public static final String DRIVER_CLASS = "driver.class";


}
?
然后是DataSourceConnectionFactory实现类:
package com.luoyu.persistence;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;

public class DataSourceConnectionFactory implements ConnectionFactory {
private static DataSourceConnectionFactory instance;
private static Properties config;
@SuppressWarnings( { "unchecked", "unused" })
private static Class driver;
private static OracleServerDataSource Orads;
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
static{
init();
}
public static void init(){
try {
config = new Properties();
config.load(ConnectionFactory.class
.getResourceAsStream("/config.properties"));
Orads= new OracleDataSource();
driver = Class.forName(config.getProperty(DRIVER_CLASS));
Orads.setUser(config.getProperty(CONNECTION_USERNAME));
SQLds.setPassword(config.getProperty(CONNECTION_PASSWORD));
Orads.setURL(config.getProperty(CONNECTION_URL));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static DataSourceConnectionFactory getInstance() {
if (instance == null) {
instance = new DataSourceConnectionFactory();
}
return instance;
}

public static void closeConnect() throws SQLException {
if (!threadLocal.get().isClosed() && threadLocal.get() != null) {
threadLocal.get().close();
}
threadLocal.set(null);
}

public static void destory() {
instance = null;
config = null;
driver = null;
Orads= null;
}
private Connection getConnect() throws SQLException {
if (threadLocal.get() == null || threadLocal.get().isClosed()) {
threadLocal.set(Orads.getConnection());
}
return threadLocal.get();
}
public static Connection getConnection()throws SQLException{
Connection connection = getInstance().getConnect();
return connection;
}
}
?
config.properties配置文件:

connection.username=system
connection.password=admin
connectino.url=jdbc:oracle:thin://localhost:1521:orcl
driver.class=oracle.jdbc.driver.OracleDriver
?

好了,问题来了,在实现类里,那个静态块显得有点多余,但我去掉后,老是报threadLocal.set(Orads.getConnection());的空指针异常,很显然数据源Orads没有初使化成功,如果把public static void init()方法改为静态块就行,但这样我在前台没法写监听器了,因为没有init()方法给我调用。。。整个采用单例设计模式,对外隐藏了getInstance()方法,只提供destory(),init().和getConnection(),所以这个问题我没法解决了....

?