您的位置:首页 > 编程语言 > Java开发

Bean的作用域

2015-12-04 16:07 417 查看
在默认的情况下所有的bean对象都是单例(在同一个spring的上下文中获取的总是同一个对象)。当spring容器分配一个bean是,它返回的bean总是同一个实例。

如果希望spring在为每次请求都生成一个新的实例的话,只需要配置bean的scope为prototype就可以了

示例

测试类:

public class TestSingle {
private Integer i;

public Integer getI() {
return i;
}

public void setI(Integer i) {
this.i = i;
}
}xml配置:
<!-- 单例 -->
<bean id="testSingle" class="com.test.createBean.TestSingle"/>
<!-- 每次调用都获取一个新的实例 -->
<bean id="testPro" class="com.test.createBean.TestSingle" scope="prototype"/>测试:
//默认获取的bean都是同一个对象
TestSingle testSingle = (TestSingle) context.getBean("testSingle");
testSingle.setI(1);
System.out.println(testSingle.getI());
TestSingle testSingle2 = (TestSingle) context.getBean("testSingle");
System.out.println(testSingle2.getI());

//通过配置变成了每次获取都是新对象
TestSingle testpro = (TestSingle) context.getBean("testPro");
testpro.setI(1);
System.out.println(testpro.getI());
TestSingle testpro2 = (TestSingle) context.getBean("testPro");
System.out.println(testpro2.getI());运行结果:
1
1
1
null
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring bean