每次我使用实例变量时Spring都会返回新实例

时间:2013-01-15 06:09:14

标签: spring inversion-of-control

我遇到了有线问题。

这是我的对象定义。

package unittest.prototypetest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("valObject")
@Scope("prototype")
public class ValueObject {
  private String value1;
  private String value2;

  //... getter and setter omitted.
}

我将组件扫描标签定义如下:

<context:component-scan base-package="unittest" scoped-proxy="targetClass" />

然后我尝试通过ApplicatioinContext获取它的实例,

//ApplicationContextHelper is a class written by me to easily create ApplicationContext
ValueObject valObject = ApplicationContextHelper.getBean("valObject");
valObject.setValue1("v1");
valObject.setValue2("v2");

System.out.println(valObject.getValue1());
System.out.println(valObject.getValue2());

最有线的结果如下所示:

2013-01-15_14:04:02.245| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'valObject'
2013-01-15_14:04:02.246| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.246| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.250| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.250| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
2013-01-15_14:04:02.252| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.295| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
null
2013-01-15_14:04:02.296| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Creating instance of bean 'scopedTarget.valObject'
2013-01-15_14:04:02.297| DEBUG | o.s.b.f.s.DefaultListableBeanFactory | Finished creating instance of bean 'scopedTarget.valObject'
null

每次我使用valObject实例时都可以看到,Spring确实为我的访问创建了一个新实例。 因此,虽然我设置了值,但系统输出打印为空。

我做错了什么吗?请提出建议,非常感谢。

1 个答案:

答案 0 :(得分:0)

您已将范围设置为原型,这是非单例。详细了解here.