gpt4 book ai didi

java - 吉斯。注入(inject)静态方法

转载 作者:行者123 更新时间:2023-11-29 04:51:00 27 4
gpt4 key购买 nike

我有一个实用方法:

public static void MyUtility(ClassWhoDoesImportantThink instance, 
Object params...){...}

通常我这样调用这个方法:

public class UsualClass{
...
@Inject
ClassWhoDoesImportantThink importantInstance;
...
public aMethod(){
...

UtilityClass.myItility(importantInstance, arg1, arg2);
...
}
}

@Inject 是 Guice 特性。但也许存在一种将“importantInstance”直接注入(inject)我的静态实用程序的方法?像:

public static void MyUtility( Object params...){
ClassWhoDoesImportantThink instance =
GuiceFeature.getObjectUsuallyInjected(ClassWhoDoesImportantThink.class);
... //Do job
}

最佳答案

MyUtility 中:

  @Inject
static ClassWhoDoesImportantThink importantInstance;

或者,或者:

  static ClassWhoDoesImportantThink importantInstance;
@Inject static void setImportantInstance(ClassWhoDoesImportantThink importantInstance) {
MyUtility.importantInstance = importantInstance;
}

并在适当的 Guice 模块 configure() 方法中:

  requestStaticInjection(MyUtility.class);

Guice 然后会在其初始设置期间注入(inject)静态变量或 setter,MyUtility 静态方法可以简单地使用静态字段。

关于java - 吉斯。注入(inject)静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com