有一个最奇怪的 Spring 问题,在使用依赖注入(inject)创建 Spring bean 之后,然后在 bean 上运行一些方法,在 bean 方法调用期间设置的实例变量都返回到它们的默认 Java 值。在我们从 Spring 2.5.5 迁移到 Spring 3.0.5 之后发现这种情况。
因此,为了清楚起见,这里是示例
原型(prototype) bean:
@Component("bean1")
@Scope("prototype")
public class Bean1{
String someString;//There are other instance variables but same happens to them
@Autowired
@Qualifier("otherBean")
private OtherBean otherBean;
public void doSomething(){
someString="1234ABC";
}
//setters and getters ....
}
以及从 spring 中获取 bean 并使用它的代码:
Bean1 bean1 = (Bean1) applicationContext.getBean("bean1");
bean1.doSomething();//updates some instance variables in bean1
String value = bean1.getSomeString(); //Instance variables is null
Object otherObject = bean1.getOtherBean(); //This Spring injected bean is correctly initialized
因此,如果我调试代码,实例变量(someString)在 doSomething 方法调用中设置在 bean 中,但在我返回后,值又回到 null。
最糟糕的是,这一切都在 2.5.5 中按预期工作,但在更新的 Spring 3.0.5 中却没有
这是遗留代码,所以我知道您应该对接口(interface)进行编码,因此 Bean1 应该是一个接口(interface),实现该接口(interface)的类应该执行实际工作。我也将代码更改为此模型,但仍然无法正常工作。
最佳答案
尝试@Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS)
关于Spring 3.0.5原型(prototype)Bean实例变量在方法调用后变为null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087613/