MongoDB Morphia in OSGi


Morphia is an object-document mapping (ODM) library for MongoDB. It may be considered as the lightweight alternative of Spring Data MongoDB or as a richer version of Jongo. Compared to Spring Data MongoDB, Morphia is simpler to setup in a non-Spring environment and it has far fewer dependencies. On the other hand, it lacks Spring Data’s uniform repository interface, and its convention-over-configuration approach that can boost productivity once a basic configuration has been setup.

The Morphia core JAR is OSGi-ready. However enabling entity class resolution in Morphia when running in OSGi requires some extra steps.

Class loading in Morphia

Morphia’s approach to entity class resolution is extensible. It delegates object construction to an instance that implements the org.mongodb.morphia.ObjectFactory interface. Morphia also provides a default implementation – org.mongodb.morphia.mapping.DefaultCreator, which given a com.mongodb.DBObject raw object, it reads its ‘className’ field, resolves the class and instantiates the respective POJO.

Fortunately, DefaultCreator delegates class resolution to a separate protected method which uses the thread-context class loader (TCCL). Although the TCCL should usually be aware of the entity classes since it is typically called from the DAO layer, this may not always be the case. E.g. in Karaf, during a Blueprint container instantiation, the TCCL is not the instantiating bundle class loader, but Karaf’s bootstrap classloader. Overriding the class loading method and delegating to an OSGi-aware classloader provides a more consistent solution.

Entity class resolution in OSGi with Morphia

Here’s a customized version of the DefaultCreator that swaps the TCCL class loader with the bundle context class loader:

public class BundleObjectFactory extends DefaultCreator {
	private BundleContext bundleContext;
	protected ClassLoader getClassLoaderForClass() {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
		return cl;

	public BundleObjectFactory(BundleContext bundleContext) {
		this.bundleContext = bundleContext;

A customized instance of the Morphia class can be created through a factory:

public class MorphiaFactory {
	private BundleContext bundleContext;	
	private List<String> classes;
	private Class<?> loadClass(String className) throws ClassNotFoundException {
		ClassLoader cl = ((BundleWiring)bundleContext.getBundle().adapt(
		return cl.loadClass(className);
	private Mapper getMapper() {
		Mapper mapper = new Mapper();	
		mapper.getOptions().objectFactory = new BundleObjectFactory(bundleContext);		
		return mapper;
	private List<Class<?>> getClassObjects(List<String> classNames) 
		throws ClassNotFoundException {
		if (classNames == null || classNames.size() == 0)
			return null;
		List<Class<?>> classObjs = new ArrayList<>();
		for (String className:classNames) {
		return classObjs;
	public Morphia get() throws ClassNotFoundException {
		Mapper mapper = getMapper();	
		List<Class<?>> classObjs = getClassObjects(classes);
		Morphia morphia = new Morphia(mapper, new HashSet<Class>(classObjs));	
		return morphia;

	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;

	public void setClasses(List<String> classes) {
		this.classes = classes;

Blueprint setup

Bringing it all together, using Blueprint for instantiation and wiring, the resulting configuration is:

<blueprint default-activation="eager"
	<cm:property-placeholder persistent-id=""/>

	<bean id="mongoClient" class="com.mongodb.MongoClient">
		<argument value="${}"/>
		<argument value="${}"/>
	<bean id="morphiaFactory" class="">
		<property name="bundleContext" ref="blueprintBundleContext"/>
		<property name="classes">
	<bean id="morphia" factory-ref="morphiaFactory" factory-method="get"/>
	<bean id="datastoreFactory" class="">
		<property name="mongoClient" ref="mongoClient"/>
		<property name="morphia" ref="morphia"/>
		<property name="database" value="${}"/>
	<bean id="datastore" factory-ref="datastoreFactory" factory-method="get"/>
	<!-- DAOs -->	
	<bean id="aclDao" class="">
		<argument ref="datastore"/>
	<bean id="principalDao" class="">
		<argument ref="datastore"/>
	<!-- Services -->
	<service ref="aclDao" interface=""/>	
	<service ref="principalDao" interface=""/>

The configuration above includes two sample DAOs that implement a simple authentication/authorization service using MongoDB as the persistent store.

The implementation of DatastoreFactory is straight-forward:

public class DatastoreFactory {
	private MongoClient mongoClient;	
	private Morphia morphia;
	private String database;
	public Datastore get() {
		return morphia.createDatastore(mongoClient, database);

	/** get/set methods */

Morphia Karaf feature

When deployed in Karaf, it is useful to group all Morphia’s dependencies into a single reusable feature that can then be referenced from other features:

<feature name="morphia" version="0.108" resolver="(obr)">
	<feature version="[1.9.13,2)">jackson</feature>
	<bundle dependency="true">mvn:org.mongodb/mongo-java-driver/2.12.2</bundle>

2 thoughts on “MongoDB Morphia in OSGi”

  1. Hello John, do you happen to have a working demo of this? It would be a great help as I’d love to use Morphia/MongoDB in Karaf 3.0.2. But I’m unable to get it to work.

  2. Hey John,
    I am studying masters and doing my master thesis.
    I have been trying to work with mongodb with morphia in Apache karaf so it would be nice if you can send me the sample code relating this.


Leave a Reply

Your email address will not be published. Required fields are marked *