问题
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"
回答1:
It is not possible using only Guice and they wont allow it.
http://code.google.com/p/google-guice/issues/detail?id=27
回答2:
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.
回答3:
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.
public interface InjectorAware {
void setInjector(Object injectingInstance);
}
public class Foo {
@Injected
public Foo(InjectorAware injectorAware){
injectorAware.setInjector(this);
}
}
That said. Not sure it's a good idea.
回答4:
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
来源:https://stackoverflow.com/questions/9027766/is-it-possible-to-inject-the-class-requesting-injection-using-guice