【发布时间】:2019-05-08 11:18:34
【问题描述】:
下面是我的模块类
public class ABCModule extends AbstractModule {
@Override
protected void configure() {
install(new JpaPersistModule(Configuration.get("error-persister")));
bind(DBService.class).to(DBServiceImpl.class).in(Singleton.class);
bind(DBRepository.class).to(DBRepositoryImpl.class).in(Singleton.class);
}
@ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
public ErrorHandler getErrorHandler() {
return new ABCHandler();
}
}
ABCHandler 有
private final DBService dbService;
@Inject
public ABCHandler() {
Injector injector = Guice.createInjector(new ABCModule());
injector.getInstance(PersistenceInitializer.class);
this.dbService = injector.getInstance(DBService.class);
}
@Override
public void handle() {
dbService.store("abc");
}
ABCModule 实例被创建并传递给一些通用模块。如您所见,ABCModule 提供了ABCHandler,ABCHandler 再次使用ABCModule 创建注入器和服务实例。它有效,但我知道这是不正确的。 Module 被调用两次。如何在 ABCHandler 内注入 dbService 而无需使用注入器或创建模块实例。我不想创建一个虚拟的空模块来创建实例。你能建议一下吗?如果我只在dbService 上使用@Inject 而不使用注入器,则它为空。我在Module 中使用Provider,可以为dbService 做类似的事情。还是有其他解决方案?
【问题讨论】:
标签: java dependency-injection guice