spring中的bean默认是单例模式

来源:互联网 发布:mobi 阅读软件 编辑:程序博客网 时间:2024/06/16 22:23

一、单例模式:在spring中其实是scope(作用范围)参数的缺省设定值
每个bean定义只生成一个对象实例,每次getBean请求获得的都是此实例
单例模式分为饿汉模式和懒汉模式,

饿汉模式
spring singleton的缺省是饿汉模式:启动容器时(即实例化容器时),为所有spring配置文件中定义的bean都生成一个实例
懒汉模式
在第一个请求时才生成一个实例,以后的请求都调用这个实例
spring singleton设置为懒汉模式:
<beans
default-lazy-init="true">

二、另一种和singleton对应的scope值---prototype多实例模式
调用getBean时,就new一个新实例
singleton和prototype的比较

singleton:
xml配置文件:
<bean id="dvdTypeDAO" class="com.terana.hibernate.impl.DvdTypeDAOImpl" />   
测试代码:
        ctx = new ClassPathXmlApplicationContext("spring-hibernate-mysql.xml");
        DvdTypeDAO tDao1 = (DvdTypeDAO)ctx.getBean("dvdTypeDAO");
        DvdTypeDAO tDao2 = (DvdTypeDAO)ctx.getBean("dvdTypeDAO");
运行:        
true
com.terana.hibernate.impl.DvdTypeDAOImpl@15b0333
com.terana.hibernate.impl.DvdTypeDAOImpl@15b0333

说明前后两次getBean()获得的是同一实例,说明spring缺省是单例

prototype:
<bean id="dvdTypeDAO" class="com.terana.hibernate.impl.DvdTypeDAOImpl" scope="prototype" />
执行同样的测试代码
运行:
false
com.terana.hibernate.impl.DvdTypeDAOImpl@afae4a
com.terana.hibernate.impl.DvdTypeDAOImpl@1db9852
说明scope="prototype"后,每次getBean()的都是不同的新实例

原创粉丝点击