Generic Bind with Guice

蹲街弑〆低调 提交于 2020-01-04 07:19:28

问题


I trying to build a simple lib for persistence with guice persist and some other things.

I already have a AbstractDao<T>, that I can easily extend and bind the concrete implementation like a boss.

But, I want a kind of GenericDao, like this:

public abstract class GenericDao<T extends Bean> {


@Inject
private Provider<EntityManager> emp;

protected EntityManager em() {
    return emp.get();
}

public AbstractDao() {
}

protected abstract Class<T> clazz();
// ....

And if I will have just the CRUD (implemented in abstract dao) in for some bean, I want to inject GenericDao<SomeBean> like a boss.

So, I started to try some hacks, and get the following:

public abstract class AbstractPersistentModule extends AbstractModule {

    protected <T extends Bean> LinkedBindingBuilder<T> bindGenericDao(final Class<T> clazz) {
       return bind(
               new TypeLiteral<GenericDao<T>>(){}
       )./* what the hell can I do here? */;
    }
}

If I can make it work, I'll be able to do a simple:

bindGenericDao(Pessoa.class);

Someone know a way to do that?


回答1:


See this post for a working implementation.




回答2:


With a lot of hacks, I finally managed it to work. Please, take a look and tell me what you think: https://github.com/namekusei/persistence/blob/master/src/main/java/com/github/namekusei/inject/AbstractPersistentModule.java




回答3:


I remember that Weld is another way to do it, you can use the @InjectionPoint's to say the type of injected element..

class Foo {
   @Inject
   private GenericDAO<Employee> dao;
   //...
}

..
@Produces
public GenericDAO<T> createDaoInstances(InjectionPoint type){
   return new GenericDAO(type.getMember().getSomeThing());
}

public GenericDAO<T>{
   //..
   public GenericDAO<T>(EntityManager em){
   //...
}

}

I think this is a more interesting, just because you can better separate the binding between components and layers.



来源:https://stackoverflow.com/questions/11318836/generic-bind-with-guice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!