Search code examples
javaosgiclassloaderapache-felixbnd

OSGi Felix and BndTools - Load class by name


In my OSGi environment I am trying to preload a database driver for further usage. Normally, this can be done like that:

Class.forName("com.mysql.jdbc.Driver");

After that, a connection can be created. However, if I use that in OSGi under Felix, he says that the class cannot be found (ClassNotFoundException) and the connection cannot be created. But when I do something like that (try-catch is omitted):

com.mysql.jdbc.Driver d = new com.mysql.jdbcDriver
Class.forName("com.mysql.jdbc.Driver");

Then everything works fine and the connection is created. However, this is not very pretty because the driver class cannot be exchanged.

Is there a way to load the class with the first method? I assume that I have to provide the correct class loader. But where do I get that from?

The MySQL driver is provided as an OSGi wrapper bundle.


Solution

  • How exactly do you create your bundle manifest? If you use tools to automatically resolve the OSGi import statements of your bundle, they will fail on the first method since they do not recognize a simple string as a package dependency. The second method expresses the dependency as a hard Java dependency, so it's recognized by the tooling which adds the required OSGi import statement (and thus by the OSGi runtime to the classpath of your bundle).

    So for your first method to work you must add the dependency to the package com.mysql.jdbc to the OSGi import statements of your bundle. How this is achieved is tool specific, Bnd uses an Import-Statement configuration parameter.