Question

I'm writing a Java EE 6 application that makes use of Morphia to persist objects to MongoDB. I'd like to be able to @Inject my DAO classes where necessary, so I created a Factory class that instantiates the DAO appropriately. It looks something like this:

public class MyDAOFactory {

    @Inject
    private Datastore mongoDatastore = null;

    /**
     * Creates the DAO
     */
    @Produces
    @ApplicationScoped
    public MyDAO createDAO() {
        MyDAO dao = new MyDAO(
                this.mongoDatastore);
        return dao;
    }
}

The code compiles fine, but when I run my application on JBoss EAP 6.1 it complains because MyDAO does not have a no-arg constructor. I would add one, but the Morphia BasicDAO class does not have one either, so I don't know that it would work that way.

Is there a way to @Inject a DAO instance into my EJB, Servlet, etc.? Or do I need to manually instantiate it every time?

Was it helpful?

Solution

It seems that CDI needs the no-arg constructor for MyDAO for some reason. Maybe because of how you use this bean (see specs ch.5.4 "Client Proxies" for possible reasons).

You cannot create a default constructor, because the base class does not have one and, from what I see from the code the super constructors make immediate use of their args. Therefore passing null to super() from a no-arg constructor will throw errors.

My suggestion is to create an interface (optionally extending org.mongodb.morphia.dao.DAO), e.g. MyDAOInterface that has all public business methods of MyDAO. Then modify MyDAO to implement this interface and change your producer to return MyDAOInterface:

public interface MyDAOInterface extends DAO {...}

public class MyDAO implements MyDAOInterface {
    // same implementation
}

public class MyDAOFactory {
    @Inject
    private Datastore mongoDatastore = null;

    /**
     * Creates the DAO
     */
    @Produces
    @ApplicationScoped
    public MyDAOInterface createDAO() {
        MyDAO dao = new MyDAO(this.mongoDatastore);
        return dao;
    }
}

By the way, programming to interfaces has the extra benefit of making your code more testable, so it is worth the minor hassle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top