对于一个小型的副项目,我正在尝试实现与数据库交互的DAO模式,并开始使用Guice(第一次)为我处理DI.现在我有这个类层次结构:
DAOImpl引用了一个类类型,因此我的数据库客户端(mongo / morphia)可以进行一些初始化工作并实例化morphia提供的BasicDAO.以下是相关类别的摘要:
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)
任何帮助将非常感激.
解决方法:
如果您需要如下所示的注射部位:
@Inject
public DAOConsumer(DAO<User> dao) {
}
被注入您的UserDAO类的实例,然后
bind(new TypeLiteral<DAO<User>>() {}).to(UserDAO.class);
至于您的其他错误:
1) No implementation for org.mongodb.morphia.Datastore was bound.
这是因为数据存储区是一个接口.您需要将接口绑定到实现,实例或Provider< Datastore>.
为了弄清楚如何做到这一点,请考虑一下您需要手动执行的步骤,而不会增加Guice的复杂性.一旦您100%理解了这一点,就可以尝试设计一个对象图,该对象图可以适当反映吗啡初始化的步骤.
首先,morphia quick tour提供了有关如何获取数据存储对象实例的指南:
final Morphia morphia = new Morphia();
// tell Morphia where to find your classes
// can be called multiple times with different packages or classes
morphia.mapPackage("org.mongodb.morphia.example");
// create the Datastore connecting to the default port on the local host
final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
datastore.ensureIndexes();
从他们的代码中,您可以看到获取数据存储区至少需要两个依赖项:
>一个单身的Morphia
>单例MongoClient
您可能必须使用Guice的Provider类编写一些代码来进行设置.