简体   繁体   中英

Is it possible to inject the class requesting injection using Guice?

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"

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.

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

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

我知道这是一个旧线程,但对于仍在尝试解决此问题的人,请查看https://github.com/raner/loginject

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM