【发布时间】:2016-11-17 04:33:53
【问题描述】:
对于我正在进行的一个小型项目,我一直在尝试为我与数据库的交互实现某种 DAO 模式,并开始使用 Guice(我第一次)为我处理 DI。现在我有这个类层次结构:
DAOImpl 引用一个类类型,因此我的数据库客户端(mongo/morphia)可以进行一些初始化工作并实例化 morphia 提供的BasicDAO。以下是相关类的 sn-ps:
public class DAOImpl<T> implements DAO<T> {
private static final Logger LOG = LoggerFactory.getLogger(DAOImpl.class);
private static final String ID_KEY = "id";
private final org.mongodb.morphia.dao.DAO morphiaDAO;
@Inject
public DAOImpl(Datastore ds, Class<T> resourceClass) {
morphiaDAO = new BasicDAO(resourceClass, ds);
LOG.info("ensuring mongodb indexes for {}", resourceClass);
morphiaDAO.getDatastore().ensureIndexes(resourceClass);
}
}
public class UserDAO extends DAOImpl<User> {
@Inject
public UserDAO(Datastore ds) {
super(ds, User.class);
}
public User findByEmail(String email) {
return findOne("email", email);
}
}
我知道我需要告诉 Guice 为每个扩展的通用 DAOImpl 绑定相关类,但我不确定该怎么做。这看起来可能已经得到回答,但它并没有为我点击。我尝试了以下一些方法:
public class AppInjector extends AbstractModule {
@Override
protected void configure() {
bind(com.wellpass.api.dao.DAO.class).to(DAOImpl.class);
// bind(new TypeLiteral<SomeInterface<String>>(){}).to(SomeImplementation.class);
// bind(new TypeLiteral<MyGenericInterface<T>>() {}).to(new TypeLiteral<MyGenericClass<T>>() {});
// bind(new TypeLiteral<DAO<User>>() {}).to(UserDAO.class);
bind(new TypeLiteral<DAO<User>>(){}).to(new TypeLiteral<DAOImpl<User>>() {});
}
}
这些是我看到的一些错误:
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for org.mongodb.morphia.Datastore was bound.
while locating org.mongodb.morphia.Datastore
for the 1st parameter of com.wellpass.api.dao.UserDAO.<init>(UserDAO.java:12)
at com.wellpass._inject.AppInjector.configure(AppInjector.java:18)
2) java.lang.Class<T> cannot be used as a key; It is not fully specified.
at com.wellpass.api.dao.DAOImpl.<init>(DAOImpl.java:19)
at com.wellpass._inject.AppInjector.configure(AppInjector.java:14)
任何帮助将不胜感激。
【问题讨论】:
标签: java generics types guice dao