Is it possible to inject the class requesting inje

2019-07-11 19:01发布

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"

4条回答
做自己的国王
2楼-- · 2019-07-11 19:25

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

查看更多
冷血范
3楼-- · 2019-07-11 19:28

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

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

查看更多
做自己的国王
4楼-- · 2019-07-11 19:33

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.

查看更多
Fickle 薄情
5楼-- · 2019-07-11 19:34

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.

查看更多
登录 后发表回答