2

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"

pbaumann
  • 652
  • 5
  • 12

4 Answers4

4

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
2

It is not possible using only Guice and they wont allow it.

http://code.google.com/p/google-guice/issues/detail?id=27

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
1

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

raner
  • 1,175
  • 1
  • 11
  • 21
1

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.

rfeak
  • 8,124
  • 29
  • 28
  • It is a solution, but for my purposes I'd prefer the injecting class not have to worry about that extra step. Thanks for the suggestion. – pbaumann Jan 27 '12 at 06:09