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

前端 未结 1 936
忘掉有多难
忘掉有多难 2021-01-06 00:15

I\'m developing a small web framework using Guice. I have a Router object that, once initialized, expose a getControllerClasses() method. I have to loop ov

相关标签:
1条回答
  • 2021-01-06 00:31

    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!

    0 讨论(0)
提交回复
热议问题