Java Spring能够处理这个用户案例吗?既不是属性也不是构造函数注入
基本上,我有一个类a,它依赖于类B,而类B又依赖于一个spring管理的bean C,但是我不想把B作为一个类变量,只是出于某种原因在一个方法中使用B。我的解决方案是在B中创建一个静态方法get(),它返回B的一个实例。现在的问题是,C没有正确地注入BJava Spring能够处理这个用户案例吗?既不是属性也不是构造函数注入,java,spring,Java,Spring,基本上,我有一个类a,它依赖于类B,而类B又依赖于一个spring管理的bean C,但是我不想把B作为一个类变量,只是出于某种原因在一个方法中使用B。我的解决方案是在B中创建一个静态方法get(),它返回B的一个实例。现在的问题是,C没有正确地注入B // A cannot have B as a class/field variable. public class A { public void method(){ // B.get() returns a inst
// A cannot have B as a class/field variable.
public class A {
public void method(){
// B.get() returns a instance of B, but this instance is not the
// instance that spring created, it is the static "instance" in B.
B.get().doSomething();// ofcourse it throws out a nullpointer exception
}
}
class B{
@Resource(name = "c")
private C c;
private static B instance;
public static B get() {
return instance==null ? (instance=new B()) : instance;
}
public void doSomething(){
c.toString(); // this line will break if c is not
// injected to the instance of b
}
}
@Service("c")
class C {
}
我该如何解决这个问题呢?您必须从Spring中以编程方式获取bean,要么在
A#method()
中,要么在A或其初始化方法的构造函数中,并缓存Spring注入的B实例。您必须从Spring中以编程方式获取bean,要么在A#method()
中,或者在A或其初始化方法的构造函数中,缓存Spring注入的B实例。使用Spring的关键在于它是一个依赖项注入框架,并且您正在A中硬编码B的依赖项
尽量不要那样做。如果不想将B存储在实例变量中,请将其作为参数传递给该方法
如果你固执地想这样做,那么你必须获得一个ApplicationContext并自己加载它。另一种方法可能是让B实现,然后让afterPropertiesSet方法使用静态实例变量注册当前实例。使用Spring的关键在于它是一个依赖项注入框架,并且您正在a中硬编码B的依赖项 尽量不要那样做。如果不想将B存储在实例变量中,请将其作为参数传递给该方法
如果你固执地想这样做,那么你必须获得一个ApplicationContext并自己加载它。另一种方法可能是让B实现,然后让afterPropertiesSet方法用静态实例变量注册当前实例。没有直接的spring支持这一点,但有一些解决问题的方法
private static B instance;
public B(){
// sets the static here
// not ideal...should use afterProperties set or what ever the Annotation equivalent is
instance = this;
}
public static B get() {
if( instance == null ){
throw new IllegalStateException("errr...say something useful here")
}
return instance;
}
public void doSomething(){
c.toString(); // this line will break if c is not
// injected to the instance of b
}
}
我看过2部。在不同的项目上使用过几次,它并不漂亮,如果你有选择的话,不要这样做,让spring来连接整个应用程序。但是如果你没有选择,它可能是最差的选择。没有直接的spring支持这一点,但是有一些解决问题的方法
private static B instance;
public B(){
// sets the static here
// not ideal...should use afterProperties set or what ever the Annotation equivalent is
instance = this;
}
public static B get() {
if( instance == null ){
throw new IllegalStateException("errr...say something useful here")
}
return instance;
}
public void doSomething(){
c.toString(); // this line will break if c is not
// injected to the instance of b
}
}
我看过2部。在不同的项目上使用过几次,它并不漂亮,如果你有选择的话,不要这样做,让spring来连接整个应用程序。但是如果你没有选择,它可能是最差的选择。为什么不可能将B注射到a?这是做这件事最正确、最“春天”的方式。我会尝试解决根本问题,而不是寻找解决办法。为什么不可能将B注入a?这是做这件事最正确、最“春天”的方式。我会尝试解决根本问题,而不是试图找到解决方法。如果要获取ApplicationContext,一种方法是实现ApplicationContextAware接口。如果要获取ApplicationContext,一种方法是实现ApplicationContextAware接口。