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的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
相关文章推荐
- 一个jar包里的网站
- 一个jar包里的网站之文件上传
- 一个jar包里的网站之返回对媒体类型
- 模拟Spring的简单实现
- spring+html5实现安全传输随机数字密码键盘
- Spring中属性注入详解
- struts2 spring整合fieldError问题
- spring的jdbctemplate的crud的基类dao
- 读取spring配置文件的方法(spring读取资源文件)
- Spring Bean基本管理实例详解
- java实现简单美女拼图游戏
- java基本教程之线程休眠 java多线程教程
- JSP开发中在spring mvc项目中实现登录账号单浏览器登录
- spring boot实战之内嵌容器tomcat配置
- 基于Spring框架的Shiro配置方法
- Spring MVC中上传文件实例
- spring aop两种配置方式
- 实例讲解Java的Spring框架中的AOP实现
- Java的Spring框架的三种连接池的基本用法示例