当springbean是value=“prototype”,proxyMode=ScopedProxyMode.TARGET\u类时,我无法保持bean的状态
以下是SpringBean:当springbean是value=“prototype”,proxyMode=ScopedProxyMode.TARGET\u类时,我无法保持bean的状态,spring,proxy,prototype,javabeans,Spring,Proxy,Prototype,Javabeans,以下是SpringBean: @Repository @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) public class TestBean { private String text; public String getText() { return text; } public void setText(String text) {
@Repository
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TestBean {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
下面是访问bean的非常简单的代码:
TestBean testBean = (TestBean) SpringContext.getBean("testBean");//#1
testBean.setText("aaaaa"); //#2
System.out.println(testBean.getText()); //#3
结果是testBean.getText为null
当我尝试调试代码时,我发现2中的testBean实例与3中的实例不同。例如:
2:TestBean@988995e
三:TestBean@69bf7e71
有什么帮助吗?谢谢 SpringContext.getBeantestBean为您返回代理对象。任何方法调用都是对DynamicAdvisedInterceptor的委托。反过来,target=getTarget;生成CglibMethodInvocation。魔法隐藏在getTarget中,它是原型bean的SimpleBanTargetSource,有一个代码:
public Object getTarget() throws Exception {
return getBeanFactory().getBean(getTargetBeanName());
}
因此,TestBean上的任何方法调用都会向BeanFactory请求该类的新实例。这就是为什么SetTextAAAA对于testBean.getText不可见的原因,因为每个方法都是针对其testBean对象的,而不是相同的
这样的原型对象不能从代码中手动更改。它们由ApplicationContext管理,只有最后一个可以填充其内部状态。从代码中,您只能读取它们
如果您的TestBean中填充了相同的值,那么您将从TestBean.getText中获得相同的值,但是所有这些调用都将针对不同的对象进行。感谢您的精彩解释!我发现如果我将其更改为ScopedProxyMode.INTERFACES,它就会工作。你能告诉我,在我从getBean获取相同的cglib代理bean之后,是否有一种方法可以获取它,而不是每次调用获取的bean的方法时都获取一个新实例?根本不要作为代理来做!因为它是原型,所以不能用代理来克服每次调用对象的问题。