标题描述了我的问题。
E.g。
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?
答案 0 :(得分:2)
这里你需要的是创建一个工厂。使用辅助注射可以帮助你。
您可以看到我的previous post regarding assisted injection
但这是您案件的确切解决方案:
EntryDAOMongoImpl:
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用作singelton(自然使用单身imo),那么您可以在模块内无需辅助注射的情况下执行以下操作:
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
}
}
如果有帮助,请告诉我