问题
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