Guice : How to bind classes that are dynamically obtained by an already binded object?

馋奶兔 提交于 2019-11-30 21:48:51

Binder is null at that point because Guice sets the binder before it calls configure(). Outside of Guice calling the Module's configure() method, there is no binder. Remember that a Module is merely a configuration file, and that it configures how the Injector behaves when you create one.

requestInjection doesn't behave like you think it does--that is, it doesn't immediately bind the fields of the instance you pass in. Instead, you're telling it to inject fields and methods as soon as someone creates the Injector. Until an Injector is created, nothing will be injected into the passed instance.

If your Router doesn't have dependencies that require Guice, then just create a new Router() and pass it as a constructor parameter into your Module. Then you can loop through your controlling classes and bind them, and also bind(Router.class).toInstance(myRouter);.

However, if your Router does depend on other modules, then you can use a child Injector. First, create an Injector, get a Router instance out of it, and then pass that Router instance into another Module that binds its controlling classes. Suddenly you'll have a module (let's call it controllingClassesModule) and you can do the following:

newInjector = originalInjector.createChildInjector(controllingClassesModule);

Then, your newInjector will inherit the bindings from your originalInjector and also all of the controlling classes that the Router specifies.

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!