spring 缺省:
测试基本bean:
改scope为多实例
使用spring 的时候, 你应该先问问自己,你编一个类,初衷,是否就是准备采用单例? 是否就是准备内部设静态实例,私有化构造方法,静态块初始化,静态getInstance() 方法?
我们可以借鉴一个框架的设计思想和经验,但不要让它帮我们做选择!!!
以此类推,spring 提供给hibernate的SessionFactory是否是单例?
sessionFactory bean 由spring的对应的SessionFactory类建立的bean, 按数据库类型,分为hibernate,JPA等几种,按操作类型,分为专为xml配置文件设计的的和专为标注设计的
sessionFactory bean 尽管是"工厂",但那是指它建立session的功能.它相对于spring来说,仍是一个普通的bean,通常把它作为属性注入到其他需要session的DAO bean中.
所以sessionFactory bean 自身的建立仍采用spring的缺省工厂类,自然缺省也是单例的.
DataSource bean 是否是单例?
DataSource bean通常把它作为属性注入到sessionFactory bean中
它自身仍是普通bean,采用spring的缺省工厂类,自然缺省也是单例的
apacha dbcp datasource
c3p0 datasource
- 1.spring用DefaultListableBeanFacto
ry.preInstantiateSingletons ()建立bean实例 - 2.缺省采用单例模式
测试基本bean:
xml配置文件: <bean id="dvdTypeDAO" class="com.machome.hibernate.impl.DvdTypeDAOImpl" /> |
测试代码: |
运行: true com.machome.hibernate.impl.DvdTypeDAOImpl@15b0333 com.machome.hibernate.impl.DvdTypeDAOImpl@15b0333 说明前后两次getBean()获得的是同一实例,说明spring缺省是单例 |
改scope为多实例
<bean id="dvdTypeDAO" class="com.machome.hibernate.impl.DvdTypeDAOImpl" scope="prototype" /> |
执行同样的测试代码 |
运行: false com.machome.hibernate.impl.DvdTypeDAOImpl@afae4a com.machome.hibernate.impl.DvdTypeDAOImpl@1db9852 说明scope="prototype"后,每次getBean()的都是不同的新实例 |
使用spring 的时候, 你应该先问问自己,你编一个类,初衷,是否就是准备采用单例? 是否就是准备内部设静态实例,私有化构造方法,静态块初始化,静态getInstance() 方法?
我们可以借鉴一个框架的设计思想和经验,但不要让它帮我们做选择!!!
以此类推,spring 提供给hibernate的SessionFactory是否是单例?
sessionFactory bean 由spring的对应的SessionFactory类建立的bean, 按数据库类型,分为hibernate,JPA等几种,按操作类型,分为专为xml配置文件设计的的和专为标注设计的
sessionFactory bean 尽管是"工厂",但那是指它建立session的功能.它相对于spring来说,仍是一个普通的bean,通常把它作为属性注入到其他需要session的DAO bean中.
所以sessionFactory bean 自身的建立仍采用spring的缺省工厂类,自然缺省也是单例的.
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" > </bean> <bean id="dvdTypeDAO" class="com.machome.hibernate.impl.DvdTypeDAOImpl"> </bean> |
测试代码: |
运行: true org.hibernate.impl.SessionFactoryImpl@12c5431 org.hibernate.impl.SessionFactoryImpl@12c5431 |
DataSource bean 是否是单例?
DataSource bean通常把它作为属性注入到sessionFactory bean中
它自身仍是普通bean,采用spring的缺省工厂类,自然缺省也是单例的
apacha dbcp datasource
|
true org.apache.commons.dbcp.BasicDataSource@ab7165 org.apache.commons.dbcp.BasicDataSource@ab7165 |
c3p0 datasource
|
true com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, ... ] com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 5, ... ] |