标题描述了我的问题。
例如
public class EntryDAOModule extends AbstractModule {
@Override
protected void configure() {
bind(EntryDAO.class).to(EntryDTOMongoImpl.class); // what should this be?
}
}
如图所示,.to
的参数应该是什么,如下所示:
public class GenericDAOMongoImpl<T, K extends Serializable> extends BasicDAO<T, K> {
public GenericDAOMongoImpl(Class<T> entityClass) throws UnknownHostException {
super(entityClass, ConnectionManager.getDataStore());
}
}
public class EntryDAOMongoImpl extends GenericDAOMongoImpl<EntryDTOMongoImpl, ObjectId> implements EntryDAO<EntryDTOMongoImpl> {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
@Inject
public EntryDAOMongoImpl(Class<EntryDTOMongoImpl> entityClass) throws UnknownHostException {
super(entityClass);
}
...
}
如何实例化 EntryDAOMongoImpl
类,如下所示:
Injector injector = Guice.createInjector(new EntryDAOModule());
this.entryDAO = injector.getInstance(EntryDAO.class); // what should this be?
最佳答案
这里您需要创建一个工厂。使用辅助注入(inject)可以帮助您。
你可以看到我的previous post regarding assisted injection
但这是适合您的情况的确切解决方案:
入口DAOMongoImpl:
public class EntryDAOMongoImpl extends GenericDAOMongoImpl<EntryDTOMongoImpl, ObjectId> implements EntryDAO<EntryDTOMongoImpl> {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
@Inject
public EntryDAOMongoImpl(@Assisted Class<EntryDTOMongoImpl> entityClass) throws UnknownHostException {
super(entityClass);
}
...
}
工厂:
public interface EntryDAOFactory {
public EntryDAOMongoImpl buildEntryDAO(Class<EntryDTOMongoImpl> entityClass);
}
模块:
public class EntryDAOModule extends AbstractModule {
@Override
protected void configure() {
//bind(EntryDAO.class).to(EntryDAOMongoImpl.class); // what should this be?
FactoryModuleBuilder factoryModuleBuilder = new FactoryModuleBuilder();
install(factoryModuleBuilder.build(EntryDAOFactory.class));
}
}
用法:
Injector injector = Guice.createInjector(new EntryDAOModule());
EntryDAOFactory factory = injector.getInstance(EntryDAOFactory.class);
this.entryDAO = factory.buildEntryDAO(entityClass);
如果您打算将 EntryDAOMongoImpl 作为单例使用(在我看来单例的自然用法),那么您可以执行以下操作,而无需在模块内进行辅助注入(inject):
public class EntryDAOModule extends AbstractModule {
@Override
protected void configure() {
EtnryDTOMongoImpl dto = new EntryDTOMongoImpl(TargetEntry.class); //guessing here
bind(EntryDAO.class).toInstance(new EntryDAOMongoImpl(dto)); // singleton
}
}
如果有帮助请告诉我
关于java - 如何在构造函数接受类的情况下使用 Guice `Module` 进行注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222870/