Auto injecting logger with guice
With reference to Guice's custom injections article, its TypeListener performs a check for InjectLogger.class annotation - which can be optional. Removing that check will inject to all Logger.class types.
class Log4JTypeListener implements TypeListener {
public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) {
for (Field field : 开发者_StackOverflow中文版typeLiteral.getRawType().getDeclaredFields()) {
if (field.getType() == Logger.class
&& field.isAnnotationPresent(InjectLogger.class)) {
typeEncounter.register(new Log4JMembersInjector<T>(field));
}
}
}
}
I'm tempted to remove "&& field.isAnnotationPresent(InjectLogger.class)" from the listener.
If we're using Guice to inject all instances of our Logger, is there any reason not to do it automatically (without need to annotate)?
I don't know of any programmatic correctness reasons why you wouldn't want to annotate.
I do think you wouldn't want to inject automatically for the sake of code clarity. Dependency Injection can have a bit of a 'magic' feel to it, annotations help clarify the magic and assist developers in understanding what is happening. Essentially, like a type for a variable, a DI annotation is as much for the developer as for the compiler/interpreter.
All that being said, I think if you weren't going to annotate for your logging classes that isn't a huge deal. Most developers don't think a ton about loggers, they just use them (at least that's been my experience). So in this case it would probably be relatively harmless.
精彩评论