Search code examples
genericsguicetypeliteral

GenericDao with Guice


I have a interface DAO<T>, and a Generic implementation of it (GenericDAO<T> implements DAO<T>).

I'll like to do something like this:

public interface UserDao extends Dao<User> {
 // code
}

// module
bind(UserDao.class).to(GenericDao.class);

Is it possible? I managed to work a inject of Dao to GenericDao automagically (I didnt create the specific userdao implementation), but, can't get this working...


Solution

  • I don't think you can bind UserDao to GenericDao. Because GenericDao does not implement UserDao, albeit both have a common ancestor. If GenericDao class has all the methods you need, then you don't need a separate UserDao class. You only need a binding as Jeff has written:

    bind(new TypeLiteral<DAO<User>>(){}).to(new TypeLiteral<GenericDAO<User>>(){});
    

    Your client classes will then depend on DAO<User>, and they will receive GenericDAO<User>. If you do need some User entity specific operations, then you should extend GenericDao<User>.

    I have written a post regarding this topic. Specifically, see the bottom of the post.