标题描述了我的问题。
Ví dụ
public class EntryDAOModule extends AbstractModule {
@Ghi đè
protected void configure() {
bind(EntryDAO.class).to(EntryDTOMongoImpl.class); // what should this be?
}
}
如图所示,.to
的参数应该是什么,给定如下:
public class GenericDAOMongoImpl extends BasicDAO {
public GenericDAOMongoImpl(Class entityClass) throws UnknownHostException {
super(entityClass, ConnectionManager.getDataStore());
}
}
public class EntryDAOMongoImpl extends GenericDAOMongoImpl implements EntryDAO {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
@Inject
public EntryDAOMongoImpl(Class 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
但这是针对您的情况的确切解决方案:
EntryDAOMongoImpl:
public class EntryDAOMongoImpl extends GenericDAOMongoImpl implements EntryDAO {
private static final Logger logger = Logger.getLogger(EntryDAOMongoImpl.class);
@Inject
public EntryDAOMongoImpl(@Assisted Class entityClass) throws UnknownHostException {
super(entityClass);
}
...
}
工厂:
public interface EntryDAOFactory {
public EntryDAOMongoImpl buildEntryDAO(Class entityClass);
}
模块:
public class EntryDAOModule extends AbstractModule {
@Ghi đè
protected void configure() {
//bind(EntryDAO.class).to(EntryDAOMongoImpl.class); // what should this be?
FactoryModuleBuilder factoryModuleBuilder = new FactoryModuleBuilder();
install(factoryModuleBuilder.build(EntryDAOFactory.class));
}
}
cách sử dụng:
Injector injector = Guice.createInjector(new EntryDAOModule());
EntryDAOFactory factory = injector.getInstance(EntryDAOFactory.class);
this.entryDAO = factory.buildEntryDAO(entityClass);
如果您打算将 EntryDAOMongoImpl 用作单例(单例 imo 的自然用法),那么您可以执行以下操作,而无需在模块中进行辅助注入(inject):
public class EntryDAOModule extends AbstractModule {
@Ghi đè
protected void configure() {
EtnryDTOMongoImpl dto = new EntryDTOMongoImpl(TargetEntry.class); //guessing here
bind(EntryDAO.class).toInstance(new EntryDAOMongoImpl(dto)); // singleton
}
}
如果有帮助请告诉我
Tôi là một lập trình viên xuất sắc, rất giỏi!