How to inject Injector?

后端 未结 4 938
太阳男子
太阳男子 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:23

    As others have already answered, you can simply use @Inject Injector because Guice defines the binding itself.

    Normally you only need one Injector in your app, and a static variable is an even easier way to store and access a singleton than injecting it. In our web app, we use stripes-guicer and get the Injector from its static method GuiceInjectorFactory.getInjector() when we need it (in our Hibernate interceptor, for example).

    I'm a little baffled by the advice that "you shouldn't use Injector directly." How else would I get an instance injected except by calling injector.getInstance() or injector.injectMembers()? There is no way. Yes, you can define Provider methods, but they will never be called unless somewhere, something uses an Injector. Yes, there are modules that use the Injector for you like the ServletModule; you have to create the Injector yourself, but you can leave it to the ServletModule after that.

    So in some circumstances, you can avoid using the Injector directly, but that doesn't mean you "shouldn't" use it. If you're using Guice alone without any optional modules, then you "should" be using an Injector all over the place because there's no other way to trigger injection. (I think developers who spend all day writing code inside frameworks sometimes forget that some people actually instantiate their own objects.)

提交回复
热议问题