Guice Custom Injection for constructor parameters

社会主义新天地 提交于 2021-01-27 05:36:36

问题


I read about Custom Injection in Guice here: https://github.com/google/guice/wiki/CustomInjections

This scheme describes how you can create a MembersInjector for injecting fields of a class. I am able to do this successfully. However, I do not like the idea of field injection and would like to do this to inject parameters of a constructor.

Does anybody have a clue as to how this can be achieved for constructor injection?

Specifically:

public class PaymentService {
  private final Logger logger;

  @Inject public PaymentService(@InjectLogger(type="log4j") final Logger logger){
       //the @InjectLogger is the injection point
  }


  ...
}

The documentation of MembersInjector says "inject dependencies into fields and methods of type T": http://google.github.io/guice/api-docs/latest/javadoc/index.html?com/google/inject/MembersInjector.html

This seems to indicate that it should be possible to do this. Any ideas?

Also, to clarify, I need to use custom injection because I don't have the binding at development time. I have to bind a logger at runtime based on the attribute in my annotation from a configuration. I also cannot iterate through all my config keys.

来源:https://stackoverflow.com/questions/34217920/guice-custom-injection-for-constructor-parameters

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