Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

Guice private parent Module expose binding to child modules

I have following Guice private module dependency tree:

public class FooModule extends PrivateModule {
    @Override
    protected void configure() {
      install(new BarModule());
      bind(Person.class);
      expose(Person.class);
    }
}

public class BarModule extends PrivateModule {
    @Override
    protected void configure() {
      install(new LifeImplModule());
      bind(Animal.class);
      expose(Animal.class);
    }
}

public class LifeImplModule extends PrivateModule {
    @Override
    protected void configure() {
      bind(Life.class).toInstance(new LifeImpl());
      expose(Life.class);
    }
}

public class Animal {
    @Inject
    public Animal(Life life) {
      //
    }
}

public class Person {
    @Inject
    public Person(Life life) {
       //
    }
}

Now when I do Guice.createInjector(new FooModule()).getInstance(Person.class) - it fails since it doesn't recognize binding for Life.class whereas Guice.createInjector(new FooModule()).getInstance(Animal.class) works since it has binding for Life via BarModule.

How do I go about solving this issue? I tried moving
install(new LifeImplModule()); to FooModule() but then Animal.class doesn't work, while Person.class does.

Could anybody explain how does Guice private module work in terms of inheriting bindings? Is install(LifeImplModule()) in FooModule not work for both Person.class and child module BarModule()?

question from:https://stackoverflow.com/questions/65894636/guice-private-parent-module-expose-binding-to-child-modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since BarModule is a private module, any modules installed inside it won't be available externally.
That's why

install(new LifeImplModule());

doesn't grant access to Life binding for FooModule. You can solve it by explicitly exposing Life from BarModule

install(new LifeImplModule());
expose(Life.class);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...