我需要测试一个JDBC数据库的连接。Java码做到这应该是简单:

DriverManager.getConnection("jdbc connection URL", "username", "password");

驾驶员理会查找合适的驱动程序给连接网址。但是我需要的是能够负荷JDBC司机(罐)在运行时间。I.电子我没有JDBC驱动程序上的类路径java运行的应用程序的代码段所述。

因此,我可以载的驾驶员使用这个代码,例如:

URLClassLoader classLoader = new URLClassLoader(new URL[]{"jar URL"}, this.getClass().getClassLoader());
Driver driver = (Driver) Class.forName("jdbc driver class name", true, classLoader).newInstance();

但随后的驱动管理仍然不会把它捡起来作为我不能告诉这类装入器到使用。我试图设置的当前线的情况类装入器,它仍然不起作用。

任何人有任何想法在最好的方式来实现?

有帮助吗?

解决方案

从这篇文章 拿起你的JDBC驱动程序在运行时;我只是要后这里的代码,以供参考。

想法是特技驾驶员管理,认为驱动器被装载系统的类装载器。要做到这一点,我们使用这类:

public class DelegatingDriver implements Driver
{
    private final Driver driver;

    public DelegatingDriver(Driver driver)
    {
        if (driver == null)
        {
            throw new IllegalArgumentException("Driver must not be null.");
        }
        this.driver = driver;
    }

    public Connection connect(String url, Properties info) throws SQLException
    {
       return driver.connect(url, info);
    }

    public boolean acceptsURL(String url) throws SQLException
    {
       return driver.acceptsURL(url);
    }

    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
    {
        return driver.getPropertyInfo(url, info);
    }

    public int getMajorVersion()
    {
        return driver.getMajorVersion();
    }

    public int getMinorVersion()
    {
        return driver.getMinorVersion();
    }

    public boolean jdbcCompliant()
    { 
        return driver.jdbcCompliant();
    }
}

这种方式的驱动程序登记册的类型 DelegatingDriver 这是装载系统的类装载器。你现在只需到负荷的司机,你真的想要使用任何类加载你想要的。例如:

URLClassLoader classLoader = new URLClassLoader(new URL[]{"path to my jdbc driver jar"}, this.getClass().getClassLoader());
Driver driver = (Driver) Class.forName("org.postgresql.Driver", true, classLoader).newInstance();
DriverManager.registerDriver(new DelegatingDriver(driver)); // register using the Delegating Driver

DriverManager.getDriver("jdbc:postgresql://host/db"); // checks that the driver is found

其他提示

问题是 DriverManager 执行"的任务,使用该立即呼叫者的类装载的实例".见准则6-3的 安全编码准则 Java编程语言,2.0版本.这类系统加载程序是没有办法特别在这种情况。

只是踢,我写了一个 博客入口 在这个问题。我的解决方案,但更复杂的然后 尼克*塞尔的解决方案, 是的更完整的,甚至从不受信任的代码。还注意 URLClassLoader.newInstance 是首选 new URLClassLoader.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top