我继承了一些在 OSGi 包中使用 Apache commons-dbcp 连接池的代码。此代码适用于 Eclipse/Equinox OSGi 版本 3.4.3 (R34x_v20081215)、commons-dbcp 1.2.2 和 springsource.org 的 postgres jdbc3 8.3.603 包。
我想现代化,也许这是我的第一个错误!
当我将新版本的 Felix 或 Equinox OSGI Cores 与新的 postgresql JDBC3 或 JDBC4 捆绑包以及最新版本的 commons-dbcp (1.4.1) 一起使用时,我遇到了类加载问题。我做了很多搜索,发现 commons-dbcp 代码应该有一个修复DBCP-214,但它似乎仍然失败。
我试图将 org.postgresql 放在 commons-dbcp MANIFEST.MF import-package 行,但这也不起作用。
我在一个激活器中编写了一个简单的测试,首先执行一个基本的 class.forName() 和 DriverManager.getConnection(),这工作正常,但是当我添加 BasicDataSource() 并设置与 BasicDataSource.getConnection() 的连接时,我得到ClassNotFoundException。请参阅下面的代码示例。
提前感谢您的任何帮助,建议,...
修!
// This one fails with an exception
public void dsTest() {
BasicDataSource bds = new BasicDataSource();
ClassLoader cl;
try {
logger.debug("ContextClassLoader: {}",
Thread.currentThread().getContextClassLoader().toString());
cl = this.getClass().getClassLoader();
logger.debug("ClassLoader: {}", cl);
if (bds.getDriverClassLoader() != null) {
logger.debug(bds.getDriverClassLoader().toString());
}
// The failure is the same with and with the setDriverClassLoader() line
bds.setDriverClassLoader(cl);
bds.setDriverClassName("org.postgresql.Driver");
bds.setUrl("jdbc:postgresql://127.0.0.1/dbname");
bds.setUsername("user");
bds.setPassword("pword");
Class.forName("org.postgresql.Driver").newInstance();
conn = bds.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM table");
conn.close();
logger.debug("Closed DataSource Test");
} catch (Exception ex) {
ex.printStackTrace();
logger.debug("Exception: {} ", ex.getMessage());
}
}
// This one works
public void managerTest() {
ClassLoader cl;
try {
cl = this.getClass().getClassLoader();
logger.debug("ClassLoader: {}", cl);
Class.forName("org.postgresql.Driver").newInstance();
String url = "jdbc:postgresql://127.0.0.1/dbname";
conn = DriverManager.getConnection(url, "user", "pword");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM table");
conn.close();
logger.debug("Closed Manger Test");
} catch (Exception ex) {
ex.printStackTrace();
logger.debug("Exception: {} ", ex.getMessage());
}
}