sách gpt4 ăn đã đi

java - 如何在构造函数接受类的地方注入(inject) Guice `Module`?

In lại Tác giả: Walker 123 更新时间:2023-11-30 09:40:54 30 4
mua khóa gpt4 giày nike

标题描述了我的问题。

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?

câu trả lời hay nhất

您在这里需要的是创建一个工厂。使用辅助注入(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
}
}

如果有帮助请告诉我

关于java - 如何在构造函数接受类的地方注入(inject) Guice `Module`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222870/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress