Guice log4j custom injection does not support logging within the constructor

点点圈 提交于 2020-01-01 17:26:37

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/6604071/guice-log4j-custom-injection-does-not-support-logging-within-the-constructor

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