2013-01-15 100 views
0

我遇到了一个有线问题。Spring每次使用实例变量都会返回新实例

这是我的对象定义。

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为我的访问创建了一个新实例。 ,以便系统输出null,尽管我设置了值。

我做错了什么?请告知,非常感谢。

+0

我不得不提到的问题是我没有设置“原型”。请看日志,每次我调用同一个valObject实例的setValue()时,Spring不应该创建一个新的实例! – Matt

回答

0

您已将范围设置为原型,这是非单身人士。阅读更多关于它here.

+0

我确实希望它是一个“原型”,因为你看到我的代码示例,它应该保持相同的实例,因为我只是问了一次。 – Matt

相关问题