与Guice通用绑定 [英] Generic Bind with Guice

查看:74
本文介绍了与Guice通用绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立一个简单的lib以实现持久性以及guice持久性和其他一些功能.

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

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

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

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

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

如果我只需要将CRUD(以抽象dao实现)放入某个bean,我想像老板一样注入GenericDao<SomeBean>.

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?

推荐答案

请参阅此

See this post for a working implementation.

这篇关于与Guice通用绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆