我有一种实用方法:
public static void MyUtility(ClassWhoDoesImportantThink instance,
Object params...){...}
通常我会这样称呼这个方法:
public class UsualClass{
...
@Inject
ClassWhoDoesImportantThink importantInstance;
...
public aMethod(){
...
UtilityClass.myItility(importantInstance, arg1, arg2);
...
}
}
@Inject是Guice的功能。 但也许存在一种注入" importantInstance"直接到我的静态工具? Smth喜欢:
public static void MyUtility( Object params...){
ClassWhoDoesImportantThink instance =
GuiceFeature.getObjectUsuallyInjected(ClassWhoDoesImportantThink.class);
... //Do job
}
答案 0 :(得分:3)
在MyUtility
:
@Inject
static ClassWhoDoesImportantThink importantInstance;
或者,或者:
static ClassWhoDoesImportantThink importantInstance;
@Inject static void setImportantInstance(ClassWhoDoesImportantThink importantInstance) {
MyUtility.importantInstance = importantInstance;
}
并使用适当的Guice模块configure()
方法:
requestStaticInjection(MyUtility.class);
然后Guice会在初始设置期间注入静态变量或setter,而MyUtility
静态方法可以简单地使用静态字段。