參考 EJB 容器管理數據源模式:XML 定義連接參數 → 啟動時載入內存 → 靜態方法 getConnection(name) 獲取連接 → 由持久化層(Processor/Listener)統一管理釋放,資源可控。
<CONNECTION-SET>
<CONNECTION name="GlobalPool" uri="java:comp/env/globalpool" driver="datasource"/>
<CONNECTION name="MysqlPool" uri="java:comp/env/mysqlpool" driver="datasource"/>
<CONNECTION name="mysql" driver="com.mysql.jdbc.Driver"
username="michelle" password="favordog" uri="jdbc:mysql://..."/>
<CONNECTION name="conn" driver="oracle.jdbc.driver.OracleDriver"
username="dcon" password="girlfriend" uri="jdbc:oracle:thin:@127.0.0.1:1521:dkt0"/>
<!-- 更多 Oracle 實例... -->
</CONNECTION-SET>
支持 datasource (JNDI 查找) 與 JDBC 直連雙模式。
public class ConnectionManager {
private static Logger logger = ...;
public static synchronized Connection getConnection() throws SQLException {
return getConnection(Repository.getInstance().getConn());
}
public static synchronized Connection getConnection(String name) throws SQLException {
dao.Connection connDef = Repository.getInstance().getConnection(name);
String driver = connDef.getDriver();
Connection cn = null;
try {
if ("datasource".equalsIgnoreCase(driver)) {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(connDef.getUri());
cn = ds.getConnection();
} else {
Class.forName(driver);
cn = DriverManager.getConnection(connDef.getUri(),
connDef.getUsername(), connDef.getPassword());
}
} catch (Exception ex) {
throw new SQLException("Connection failed: " + ex.getMessage());
}
return cn;
}
// 重載支持直接傳入 dao.Connection 對象
// main 方法支持命令行測試
}
Connection conn = ConnectionManager.getConnection("conn");
一行代碼獲取指定數據庫連接,屏蔽底層差異,輕量級應用亦能優雅應對多數據源環境。