How to inject Injector?

后端 未结 4 939
太阳男子
太阳男子 2020-12-13 13:39

Situation: i need lazy dependency instantiation in some FooClass, so i pass Injector to class as a constructor parameter.

private f         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 14:21

    As @gpampara said, Provider should be used for lazy/optional initialization. Also, as I said in my answer to your other question, you should be avoiding references to the Injector in your code in almost all cases.

    That said, in a class that is created by Guice, the Injector that is creating the object can be injected just by declaring a dependency on Injector. The Injector is automatically available for injection without you declaring any binding for it.

    If you do inject the Injector, you should think about WHY you want to do that. Why don't you just declare dependencies on the actual interfaces/classes the class depends on? It's just as easy to add a new dependency to the constructor as it is to retrieve an instance of some dependency through the Injector elsewhere in your code, and it makes the code far more understandable as well.

提交回复
热议问题