2

我试图用 guice persist 和其他一些东西来构建一个简单的持久化库。

我已经有一个AbstractDao<T>,我可以像老板一样轻松地扩展和绑定具体的实现。

但是,我想要一种 GenericDao,像这样:

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();
// ....

如果我将只有 CRUD(在抽象 dao 中实现)用于某个 bean,我想像GenericDao<SomeBean>老板一样注入。

所以,我开始尝试一些技巧,并得到以下结果:

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? */;
    }
}

如果我能让它工作,我将能够做一个简单的:

bindGenericDao(Pessoa.class);

有人知道这样做的方法吗?

4

3 回答 3

2

有关工作实施,请参阅此帖子。

于 2012-07-26T10:17:15.020 回答
1

经过很多黑客攻击,我终于设法让它工作了。请看一下并告诉我您的想法:https ://github.com/namekusei/persistence/blob/master/src/main/java/com/github/namekusei/inject/AbstractPersistentModule.java

于 2012-07-04T11:16:28.877 回答
1

我记得 Weld 是另一种方法,您可以使用@InjectionPoint 来说明注入元素的类型。

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){
   //...
}

}

我认为这是一个更有趣的,只是因为你可以更好地分离组件和层之间的绑定。

于 2012-07-04T11:38:32.100 回答