db4o can run in an OSGi environment. db4o jars have a OSGi manifest so that you can use them in your project.
In principal you can use db4o in OSGi without any special configuration, as long as the stored objects and db4o are loaded with the same OSGi classloader.
However as soon as you're using multiple bundles, and therefore multiple classloaders, you need to configure db4o. You can specify the class-loader explicitly for db4o, or even use multiple class-loaders. This way you can lookup in multiple class-loaders for your class. First write an implementation of the JdkLoader interface:
class OSGiLoader implements JdkLoader{ private final Bundle[] bundlesToLookIn; OSGiLoader(Bundle... bundlesToLookIn) { this.bundlesToLookIn = bundlesToLookIn; } public Class loadClass(String s) { for (Bundle bundle : bundlesToLookIn) { try { return bundle.loadClass(s); } catch (ClassNotFoundException e) { // just retry on other bundles } } try { return getClass().getClassLoader().loadClass(s); } catch (ClassNotFoundException e) { return null; } } public Object deepClone(Object o) { return new OSGiLoader(bundlesToLookIn); } }
After that you can use your implementation to load classes for db4o:
// Specify the bundles from which the classes are used to store objects Bundle[] bundles = new Bundle[]{bundleContext.getBundle()}; EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration(); configuration.common() .reflectWith(new JdkReflector(new OSGiLoader(bundles)));
Note also that some db4o jars have a dependency on Ant and need an Ant bundle in your OSGi application to use all features.
An alternative is to use the db4o OSGi package, which is in the db4o--X.XX-osgi.jar and includes all dependencies. See "Dependency Overview". This provides a OSGi service which creates a db4o instance for you. It configures db4o in such a way that classes are loaded from the requesting OSGi service.
ServiceReference reference = bundleContext.getServiceReference("com.db4o.osgi.Db4oService"); Db4oService db4oService = (Db4oService) bundleContext.getService(reference); ObjectContainer container = db4oService.openFile("database.db4o");