Guice log4j 自定义注入不支持在构造函数内进行日志记录
我正在尝试使用 Guice 将 Log4J Logger 实例注入类中,如 Guice 文档中所述:
http://code.google.com/p/google-guice/wiki/CustomInjections
但是,正如该 wiki 页面上的一些评论所述,此方案不支持构造函数注入。所以我不能这样做:
public class Foo {
@InjectLogger Logger logger;
@Inject
public Foo(<injected parameters>) {
logger.info("this won't work because logger hasn't been injected yet");
...
}
public bar() {
logger.info("this will work because by the time bar() is called,")
logger.info("the logger has been injected");
}
}
是否有另一种方法来处理此注入,以便及时注入记录器供构造函数使用?
I'm trying to use Guice to inject Log4J Logger instances into classes as described in the Guice documentation:
http://code.google.com/p/google-guice/wiki/CustomInjections
However, as noted in some of the comments on that wiki page, this scheme does not support a constructor injection. So I can't do this:
public class Foo {
@InjectLogger Logger logger;
@Inject
public Foo(<injected parameters>) {
logger.info("this won't work because logger hasn't been injected yet");
...
}
public bar() {
logger.info("this will work because by the time bar() is called,")
logger.info("the logger has been injected");
}
}
Is there another way to handle this injection so that the logger is injected in time for the constructor to use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢 jfpoilpret 的帮助,我能够得到我想要的行为。当 Logger 变量修改为静态时,我在hear() 中使用了条件来利用反射,否则它使用正常的 Guice 字段注入。
Thanks to the help from jfpoilpret, I was able to get the behavior I wanted. I used a conditional in hear() to leverage reflection when the Logger variable is modified as static, otherwise it uses normal Guice field injection.