gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:40:54 30 4
gpt4 key购买 nike

标题描述了我的问题。

例如

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

但这是针对您的情况的确切解决方案:

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 用作单例(单例 imo 的自然用法),那么您可以执行以下操作,而无需在模块中进行辅助注入(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 - 如何在构造函数接受类的地方注入(inject) Guice `Module`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9222870/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com