【发布时间】:2011-12-26 14:53:54
【问题描述】:
有一个最奇怪的 Spring 问题,在使用依赖注入创建 Spring bean,然后在 bean 上运行一些方法后,在 bean 方法调用期间设置的实例变量都返回到它们的默认 Java 值。在我们从 Spring 2.5.5 迁移到 Spring 3.0.5 后发现这种情况。
为了清楚起见,这里是示例
原型 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 中却没有
这是遗留代码,所以我知道您应该对接口进行编码,因此 Bean1 应该是一个接口,实现该接口的类应该执行实际工作。我也将代码更改为此模型,但仍然无法正常工作。
【问题讨论】:
标签: spring dependency-injection