Search code examples
javadependency-injectionguice

guice injection without injector


Below is my module class

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();
    }
}

and ABCHandler has

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 instance gets created and gets passed to some generic module. As you can see ABCModule provides ABCHandler and ABCHandler again uses ABCModule to create injector and service instance. It works but I know it is not correct. Module is called twice. How do I inject dbService inside ABCHandler without having to use injector or creating module instance. I don't want to create a dummy empty module just to creates instances. can you please suggest. If I just use @Inject on dbService without using injector, it comes as null. I am using Provider inside Module, can something similar done for dbService. Or any other solutions?


Solution

  • DbService is already injectable and you can pass it in getErrorHandler method

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

    In this case ABCHandler constructor can be changed to this

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

    More details you can find here Accessing Guice injector in its Module?