Guice log4j自定义注入不支持在构造函数中进行日志记录 [英] Guice log4j custom injection does not support logging within the constructor
问题描述
我正在尝试使用Guice将Log4J Logger实例注入到Guice文档中所述的类中:
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
但是,正如该Wiki页面上的一些注释所指出的那样,此方案不支持构造函数注入.所以我不能这样做:
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?
推荐答案
借助jfpoilpret的帮助,我能够获得想要的行为.当Logger变量被修改为静态时,我在listen()中使用了条件反射来利用反射,否则它将使用常规的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.
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
for (Field field : typeLiteral.getRawType().getDeclaredFields()) {
if (field.getType() == Logger.class && field.isAnnotationPresent(InjectLogger.class)) {
if (Modifier.isStatic(field.getModifiers())) {
// use reflection
try {
field.setAccessible(true);
Logger logger = Logger.getLogger(field.getDeclaringClass());
field.set(null, logger);
} catch (IllegalAccessException iae) { }
} else {
// register a member injector
Log4JMembersInjector<T> memberInjector = new Log4JMembersInjector<T>(field);
typeEncounter.register(memberInjector);
}
}
}
}
这篇关于Guice log4j自定义注入不支持在构造函数中进行日志记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!