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

Spring集成Hibernate 理解LocalSessionFactoryBean

2012-06-30 13:33 579 查看
LocalSessionFactoryBean(org.springframework.orm.hibernate3.LocalSessionFactoryBean)是Spring和Hibernate集成的重要类。

<bean id="MySf" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>

<property name="mappingResources">
<list>
<value>org/hzy/entity/Dept.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 	<prop key="hibernate.current_session_context_class">thread</prop> -->
<prop key="hibernate.current_session_context_class">
org.springframework.orm.hibernate3.SpringSessionContext
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>


从下面的配置文件可以看出,配置文件中的sessionFactory按照道理说,应该是LocalSessionFactoryBean的实例,但是实际上却不是,而是SessionFactory的实例。

public class LocalSessionFactoryBean extends AbstractSessionFactoryBean implements BeanClassLoaderAware

public abstract class AbstractSessionFactoryBean
implements FactoryBean<SessionFactory>, InitializingBean, DisposableBean, PersistenceExceptionTranslator


从源码中,我们可以看出LocalSessionFactoryBean它继承了父类AbstractSessionFactoryBean,父类实现了FactoryBean<T>接口,并给了SessionFactory类型
Spring给我们提供了强大的接口FactoryBean<T>,该接口有三个方法(getObject(),getObjectType(),isSingleton()):
只要它的实现类实现了getObject()方法,Spring则返回getObject()返回出来的对象,当引用当引用这个LocalSessionFactoryBean 的时候,比如applicationContext.getBean("MySf")这样,spring返回的不是LocalSessionFactoryBean 本身,他的父类AbstractSessionFactoryBean会调用getObject()这个方法,把真正的sessionfactory返回。

例如:以前 类A_factory(id="a")——>getBean("a")得到一个new A_factory()对象,
现在则是getBean("a")得到new
A_factory().getObject()。
例子:

package org.hzy.dao;

import org.springframework.beans.factory.FactoryBean;
/**
* TestBean继承了FactoryBean接口
* @author Administrator
*
*/
public class DeptFactory implements FactoryBean<Dept>{

public Dept getObject() throws Exception {
// TODO Auto-generated method stub
return new Dept(10);
}

public Class<?> getObjectType() {
// TODO Auto-generated method stub
return null;
}

public boolean isSingleton() {
// TODO Auto-generated method stub
return false;
}
}
配置:

<bean id="Dept" class="org.hzy.dao.DeptFactory"></bean>


测试:

public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans1.xml");
//		DeptFactory d=ctx.getBean("Dept",DeptFactory.class);
Dept d=ctx.getBean("Dept",Dept.class);
System.out.println(d);
}


注:上面的结果返回的是Dept类型,而不是DeptFactory类型,
由于DeptFactory实现了FactoryBean接口,把Dept类型传进去,当你向Spring要DeptFactory对象时,将会调用DeptFactory中的getObject()方法,所以返回

结果是Dept对象。(当你向Spring
要Dept类型,spring 还是同样返回通过getObject产生的对象),这里列举的是Dept类型,其它类型也是一样的

DeptFactory d=ctx.getBean("&Dept",DeptFactory.class);


bean的id前加个&得到的就是DeptFactory类型,真正的类型
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息