我正在使用 Java CDI 来实现 bean 生命周期。
@Named
public class ManagedBeanClass{
...
public ManagedProfile getManagedProfile(){
return new ManagedProfile();//logic will goes here
}
}
例如
public class sample1{
@Inject private ManagedBeanClass managedBeanClass;
...
public static boolean methodExample() throws Exception{
ManagedProfile managedProfile = managedBeanClass.getManagedProfile();
....
}
}
尝试将托管bean注入(inject)(@Inject)静态方法,它显示comaliaton错误
Cannot make a static reference to the non-static field managedBeanClass
陷入 Context DI 和静态对象生命周期的困境。 提前帮我解决这个问题。
最佳答案
示例代码中的问题与 CDI 无关;您正在尝试从静态方法访问非静态字段 (managementBeanClass
)。这在 Java 中是不可能的(无论有没有 CDI)。
此外,静态方法几乎总是指向设计问题 (*)。拥有这样的静态方法会使您的程序更难以测试并且更难以更改/维护。尝试提出一种根本不需要静态方法的设计......
所以,简短的答案是:不要。
但是,如果您确实必须在这里有一个静态方法,则可以使用构造函数注入(inject)并从构造函数设置一个静态字段。 但要注意:这有潜在的危险,因为每个新实例都会再次设置字段(这可能会导致竞争条件和意外行为)。
(另请参阅:https://stackoverflow.com/a/22068572/10363398)
(*) 除了少数异常(exception),例如 Math 类中的方法。但这些都是非常小的纯函数,没有副作用。
关于java - 如何将托管bean(非静态)注入(inject)静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53084716/