Guice log4j自定义注入不支持在构造函数中进行日志记录

时间:2011-07-06 23:04:35

标签: java logging dependency-injection guice

我正在尝试使用Guice将Log4J Logger实例注入到Guice文档中描述的类中:

http://code.google.com/p/google-guice/wiki/CustomInjections

但是,正如该维基页面上的一些评论中所述,此方案不支持构造函数注入。所以我不能这样做:

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");
    }
}

是否有另一种处理此注入的方法,以便及时注入记录器以供构造函数使用?

1 个答案:

答案 0 :(得分:6)

感谢jfpoilpret的帮助,我得到了我想要的行为。当Logger变量被修改为静态时,我在listen()中使用条件来利用反射,否则它使用普通的Guice字段注入。

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);
            }
        }
    }
}