简体   繁体   English

是否可以使用Guice注入请求注射的类?

[英]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? 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" 当NeedsInjectorAwareField被注入时,控制台将打印“我被注入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. Guice实际上已经为你注入了一个java.util.logging.Logger ,它已经使用它注入的类的名称进行了自定义。 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. 不确定它是如何完成的,但你可以借用Guice源中使用的技术......或者直接使用Logger。

UPDATE: this appears to be the point of the Guice source responsible for this behavior. 更新: 似乎是Guice来源负责此行为的要点。 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. 只使用Guice是不可能的,他们不会允许它。

http://code.google.com/p/google-guice/issues/detail?id=27 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. 不确定你是否只能使用Guice来完成它,但是通过注入的构造函数使它工作并不会太难。

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. 不确定这是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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