Autowiring Morphia entities

My current project is using Morphia to handle object mapping to/from mongoDB and I wanted to add dependency injection using Spring to my entities like this:

@Entity
public class MyEntity {
...
    @Autowired @Transient
    private SomeService someService;

}

Notice the @Transient annotation that tells Morphia to avoid persisting this field! I solved this problem by adding an EntityInterceptor that autowires all entities:

public class SpringAutowiringEntityInterceptor extends AbstractEntityInterceptor {
	@Autowired
	private ApplicationContext applicationContext;

    @Autowired
    private Morphia morphia;

	@PostConstruct
	public void postConstruct() {
		morphia.getMapper().addInterceptor(this);
	}

	@Override
	public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {
		applicationContext.getAutowireCapableBeanFactory().autowireBean(ent);
	}
}

Here is the complete source code SpringAutowiringEntityInterceptor.java. Let me know what you think!

Leave a Reply

Close Menu