简体   繁体   中英

Inject one bean into another with annotations in Guice

I am new to Guice so this might be a basic question. Guice beans get created correctly with below code in Module

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        ClassA classAObj = ClassA.standard().build();
        bind(ClassA.class).toInstance(classAObj);
        ClassB classBObj = new ClassB(classAObj);
        bind(ClassA.class).toInstance(classBObj);
    }
}

but I want to create beans for ClassA and ClassB using annotations. I tried below code in Module:

public class MyModule extends AbstractModule {
    @Provides @Singleton public ClassA getClassA() {
        return ClassA.standard().build();
    }
    @Provides @Singleton public ClassB getClassB() {
        Injector injector = Guice.createInjector(new MyModule());
        return new ClassB(injector.getInstance(ClassA.class));
    }
}

I also tried few other combinations but they don't seem to be working. Can someone please let me know

  1. How to inject bean of ClassA as constructor parameter while creating bean of ClassB using annotations in Guice?

AND/OR

  1. How to set bean of ClassA as class level variable of ClassB(without constructor route)?

You can simply write the following:

@Provides @Singleton
public ClassB getClassB(ClassA classA) {
  return new ClassB(classA);
}

By passing ClassA as parameter of getClassB , Guice will consider that ClassB depends on ClassA , and will know that it must call getClassA() before calling getClassB(ClassA) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM