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:

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 {
	private ApplicationContext applicationContext;

    private Morphia morphia;

	public void postConstruct() {

	public void preLoad(Object ent, DBObject dbObj, Mapper mapr) {

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

Leave a Reply