2

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...

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
caarlos0
  • 20,020
  • 27
  • 85
  • 160
  • possible duplicate of [Inject Generic Implementation using Guice](http://stackoverflow.com/questions/4238919/inject-generic-implementation-using-guice) – A.H. Jul 26 '12 at 07:44

2 Answers2

3

You have to ultimately choose a type for T in order to actually use the generic class. For each type you end up using, you need to create a binding like this (using Integer for T) as an example:

bind(new TypeLiteral<DAO<Integer>>(){})
   .to(new TypeLiteral<GenericDAO<Integer>>(){});
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
2

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.

Jamol
  • 2,281
  • 2
  • 28
  • 28