![](/img/trans.png)
[英]How to use guice injection to inject a Class in a class with static methods?
[英]Is it possible to inject the class requesting injection using Guice?
我想要一個對象的注入實例來知道請求注入的類的名稱。 我知道這種違反了依賴注入的整個概念,但它似乎是支持有用日志記錄的有效用例。 Guice可以實現嗎?
例:
class InjectorAware {
@Inject
public InjectorAware(Class injectorClass){
System.out.println("I was injected into a "+injectorClass.getCanonicalName());
}
}
class NeedsInjectorAwareField {
@Inject InjectorAware injectorAware;
}
當NeedsInjectorAwareField被注入時,控制台將打印“我被注入somepackage.NeedsInjectorAwareField”
只使用Guice是不可能的,他們不會允許它。
我知道這是一個舊線程,但對於仍在嘗試解決此問題的人,請查看https://github.com/raner/loginject
不確定你是否只能使用Guice來完成它,但是通過注入的構造函數使它工作並不會太難。
public interface InjectorAware {
void setInjector(Object injectingInstance);
}
public class Foo {
@Injected
public Foo(InjectorAware injectorAware){
injectorAware.setInjector(this);
}
}
那就是說。 不確定這是個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.