I'd like an injected instance of an object to know the name of the class that is requesting its injection. I'm aware that this kind of violates the entire concept of dependency injection, but it seems like a valid use case for supporting useful logging. Is this possible with Guice?
Example:
class InjectorAware {
@Inject
public InjectorAware(Class injectorClass){
System.out.println("I was injected into a "+injectorClass.getCanonicalName());
}
}
class NeedsInjectorAwareField {
@Inject InjectorAware injectorAware;
}
When NeedsInjectorAwareField gets injected, the console would print "I was injected into a somepackage.NeedsInjectorAwareField"
I know it's an old thread, but for those folks who are still trying to solve this problem, have a look at https://github.com/raner/loginject
It is not possible using only Guice and they wont allow it.
http://code.google.com/p/google-guice/issues/detail?id=27
Guice actually already injects a
java.util.logging.Logger
for you that already is customized with the name of the class it's injected into. Not sure how it's done, but you might be able to borrow the technique used from the Guice source...or just use the Logger directly.UPDATE: this appears to be the point of the Guice source responsible for this behavior. You might be able to borrow the technique somehow, I'm not sure.
Not sure if you could do it only with Guice, but it wouldn't be too hard to make it work through the injected constructors.
That said. Not sure it's a good idea.