Load JDBC Driver without name from external JAR

dan1st :

I want the user to decide what database to use. He should just provide the connector JAR file and the database URL.

The problem is, that I don't know the class name of the driver.

Is it possible to load the JAR using a URLClassLoader and register the driver without knowing the name. Until now, I only found solutions where the driver name is known.

I also tried to add a directory relative to the classpath of my exported JAR file (using maven assembly plugin) but it did not work.

<configuration>
    <archive>
        <manifest>
            <addClasspath>true</addClasspath>
        </manifest>
        <manifestEntries>
            <Class-Path>libs/*</Class-Path>
        </manifestEntries>
    </archive>
</configuration>

Any help would be appreciated.

Mark Rotteveel :

All JDBC 4 and higher compliant drivers contain a service definition file for use with java.util.ServiceLoader. If your application has the driver on the initial class path, you don't need to do anything, as java.sql.DriverManager will automatically load these drivers.

If the driver is on a secondary class path (eg in a web application context, or a manually initialized class loader), then you will need to manually load the driver to get it registered. In that case it should be possible to use ServiceLoader yourself to enumerate all available drivers on the class path of that context.

This can be done with ServiceLoader.load​(Class<S> service) or ServiceLoader.load​(Class<S> service, ClassLoader loader). You can then iterate (or stream) instances of the available drivers (which will automatically register them with DriverManager).

Eg

ServiceLoader<Driver> drivers = ServiceLoader.load(java.sql.Driver.class, yourClassLoader);
for (Driver driver : drivers) {
    System.out.println(driver.getClass().getName());
}

The only thing you will need to know is the correct JDBC url to connect.

Please take into account that this can cause a memory leak if your class loader has a short lifetime: you will need to explicitly deregister the driver to avoid such a leak.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324827&siteId=1