【问题标题】:guice injection without injector无注射器的guice注射
【发布时间】: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 提供了ABCHandlerABCHandler 再次使用ABCModule 创建注入器和服务实例。它有效,但我知道这是不正确的。 Module 被调用两次。如何在 ABCHandler 内注入 dbService 而无需使用注入器或创建模块实例。我不想创建一个虚拟的空模块来创建实例。你能建议一下吗?如果我只在dbService 上使用@Inject 而不使用注入器,则它为空。我在Module 中使用Provider,可以为dbService 做类似的事情。还是有其他解决方案?

【问题讨论】:

    标签: java dependency-injection guice


    【解决方案1】:

    DbService 已经是可注入的,你可以在getErrorHandler 方法中传递它

      @ProvidesIntoOptional(ProvidesIntoOptional.Type.ACTUAL)
      public ErrorHandler getErrorHandler(DBService dbService) {
        return new ABCHandler(dbService);
      }
    

    这种情况下ABCHandler构造函数可以改成this

      @Inject
      public ABCHandler(DBService dbService) {
        this.dbService = dbService;
      }
    

    您可以在此处找到更多详细信息 Accessing Guice injector in its Module?

    【讨论】:

    • 非常感谢,很有帮助。
    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多