开发者

Guice log4j custom injection does not support logging within the constructor

开发者 https://www.devze.com 2023-03-18 22:51 出处:网络
I\'m trying to use Guice to inject Log4J Logger instances into classes as described in the Guice documentation:

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 i开发者_Python百科njection. 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消