Spring学习心得(4)-- Spring容器创建对象的单/多例
2017-03-14 11:30
399 查看
在前面,我们讨论到了spring容器创建对象的3种方式以及spring容器创建对象的时机,那么我们现在来讨论一下spring容器创建对象的单/多例
那么
首先,我们要先用2个引用对象得到这个对象,判断它们的hashcode.
运行之后的结果为:
我们可以看到,两个引用对象输出的hashCode是一样的,那么就是说spring容器默认创建的对象是单例的。
首先spring的配置文件的bean中有一个scope属性,其取值为:singleton/prototype/request/session
大致内容是说:singleton是默认的取值,当客户端调用该对象的时候,返回的时一个单利的对象。而prototype返回的是一个多例的对象,在每一次调用的时候,都返回一个新的对象。而request/session等取值,是在web环境下使用。
还有一个特点就是,当我们使用了scope的值为prototype的时候,spring创建对象的时机也会变成当我们调用某个对象的时候才创建相应的对象
配置文件中的代码为:
由上可以得到,当scope取值为prototype的时候,客户端在调用某个类的时候,spring容器才创建相应的对象
当scpose为prototype时,始终在context.getBean时创建对象
那么
怎样判断spring容器创建的对象是单例还是多例呢?
public class testHelloSpring { /** * 判断spring容器创建的对象是单例/还是多例 */ @Test public void test1(){ //启动spring容器 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); //得到helloSpring对象 helloSpring helloSpring=(helloSpring) applicationContext.getBean("hello"); helloSpring helloSpring2=(helloSpring) applicationContext.getBean("hello"); //对比这两个引用对象的hashcode System.out.println(helloSpring); System.out.println(helloSpring2); } }
首先,我们要先用2个引用对象得到这个对象,判断它们的hashcode.
运行之后的结果为:
我们可以看到,两个引用对象输出的hashCode是一样的,那么就是说spring容器默认创建的对象是单例的。
那么如何设置spring产生的对象为多例呢?
首先spring的配置文件的bean中有一个scope属性,其取值为:singleton/prototype/request/session大致内容是说:singleton是默认的取值,当客户端调用该对象的时候,返回的时一个单利的对象。而prototype返回的是一个多例的对象,在每一次调用的时候,都返回一个新的对象。而request/session等取值,是在web环境下使用。
还有一个特点就是,当我们使用了scope的值为prototype的时候,spring创建对象的时机也会变成当我们调用某个对象的时候才创建相应的对象
配置文件中的代码为:
<bean class="cn.ansel.domain.helloSpring" id="hello" lazy-init="true" scope="prototype"></bean>测试类的代码为:
public class testHelloSpring { /** * 测试配置文件中scope的取值为prototype时,对象的创建时机 */ @Test public void test1(){ //启动spring容器 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); System.out.println(" scope is prototype"); //得到helloSpring对象 helloSpring helloSpring=(helloSpring) applicationContext.getBean("hello"); } }运行结果为:
由上可以得到,当scope取值为prototype的时候,客户端在调用某个类的时候,spring容器才创建相应的对象
创建时机和scope的结合
Scope为prototype,lazy-init为true
在context.getBean时创建对象Scopse为prototype,lazy-init为false
在context.getBean时创建对象,lazy-init为false失效当scpose为prototype时,始终在context.getBean时创建对象
Scopse为singleton
是默认情况相关文章推荐
- Spring学习心得(3)-- Spring容器创建对象的时机
- Spring学习心得(5)-- spring容器创建对象的生命周期
- scope的取值对spring容器创建对象的单/多例的影响
- spring学习教程7-spring容器创建bean对象的方式以及如何处理多个spring配置文件
- Spring学习心得(2)-- 创建对象的方式
- spring in action 学习笔记三:对spring 容器的理解,以及如何利用AnnotationConfigApplicationContext这个容器创建对象
- SpringIOC容器-创建对象
- 手动创建(new)对象,使用spring容器中的bean(ServletContext)。
- spring容器创建对象的3种方式(bean的实例化)
- 【Spring源码--IOC容器的实现】(五)Bean对象的创建
- spring IOC容器创建对象的三种方式
- spring接口 BeanFactoryAware,动态获取IOC容器里面的对象(多例)
- Syline6.5学习心得-web-创建几何对象
- spring 之脱离容器管理创建的对象进行依赖注入
- spring学习(五)—通过注解方式创建对象和注入属性
- Spring的核心之IoC容器创建对象
- 79——SpringIOC容器创建对象的方式?(2条)
- spring容器创建对象的生命周期
- spring容器IOC创建对象<二>
- spring(IOC) 对象创建时机、对象作用域scope、对象的初始化方法和销毁方法的调用、spring容器总结