For a small side project I'm working on I've been trying to implement something of a DAO pattern for my interactions with the DB, and have started using Guice (for my first time) to handle the DI for me. Right now I have this class hierarchy:
DAOImpl
takes a reference to a class type so my database client (mongo/morphia) can do some initialization work and instantiate a BasicDAO
provided by morphia. Here's snippets of the relevant classes:
public class DAOImpl<T> implements DAO<T> { private static final Logger LOG = LoggerFactory.getLogger(DAOImpl.class); private static final String ID_KEY = "id"; private final org.mongodb.morphia.dao.DAO morphiaDAO; @Inject public DAOImpl(Datastore ds, Class<T> resourceClass) { morphiaDAO = new BasicDAO(resourceClass, ds); LOG.info("ensuring mongodb indexes for {}", resourceClass); morphiaDAO.getDatastore().ensureIndexes(resourceClass); } } public class UserDAO extends DAOImpl<User> { @Inject public UserDAO(Datastore ds) { super(ds, User.class); } public User findByEmail(String email) { return findOne("email", email); } }
I know that I need to tell Guice to bind the relevant classes for each generic DAOImpl
that gets extended, but I'm unsure of how to do it. This looks like it might have been answered but it's not clicking for me. I've tried some of the following:
public class AppInjector extends AbstractModule { @Override protected void configure() { bind(com.wellpass.api.dao.DAO.class).to(DAOImpl.class); // bind(new TypeLiteral<SomeInterface<String>>(){}).to(SomeImplementation.class); // bind(new TypeLiteral<MyGenericInterface<T>>() {}).to(new TypeLiteral<MyGenericClass<T>>() {}); // bind(new TypeLiteral<DAO<User>>() {}).to(UserDAO.class); bind(new TypeLiteral<DAO<User>>(){}).to(new TypeLiteral<DAOImpl<User>>() {}); } }
These are some of the the errors I've seen:
com.google.inject.CreationException: Unable to create injector, see the following errors: 1) No implementation for org.mongodb.morphia.Datastore was bound. while locating org.mongodb.morphia.Datastore for the 1st parameter of com.wellpass.api.dao.UserDAO.<init>(UserDAO.java:12) at com.wellpass._inject.AppInjector.configure(AppInjector.java:18) 2) java.lang.Class<T> cannot be used as a key; It is not fully specified. at com.wellpass.api.dao.DAOImpl.<init>(DAOImpl.java:19) at com.wellpass._inject.AppInjector.configure(AppInjector.java:14)
Any help would be much appreciated.