org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑解决办法

  在项目中使用了SSH框架(Struts2 + Spring3+ Hibernate3),applicationContext中配置了sessionFactory

"sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  "dataSource" ref="dataSource">
  "hibernateProperties">
  
  "hibernate.dialect" >org.hibernate.dialect.SQLServerDialect
  "hibernate.jdbc.batch_size">20
  "hibernate.show_sql">true
  
  
  "mappingResources">
  
  com/jw/pojo/JwUser.hbm.xml
  
  
  

在junit4中定义了一个测试

@Test
public void beanSessionFactoryTest(){
  LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)appContext.getBean("sessionFactory");
}

运行测试的时候报了一个异常

Testcase: beanSessionFactoryTest(com.test.spring.SpringBeanTest): Caused an ERROR
org.hibernate.impl.SessionFactoryImpl cannot be cast to org.springframework.orm.hibernate3.LocalSessionFactoryBean
java.lang.ClassCastException: org.hibernate.impl.SessionFactoryImpl cannot be cast to org.springframework.orm.hibernate3.LocalSessionFactoryBean

问题分析:

  LocalSessionFactoryBean实现了org.springframework.beans.factory.FactoryBean接口, spring在装配的时候, 如果发现实现了org.springframework.beans.factory.FactoryBean接口, 就会使用FactoryBean#getObject() 方法返回的对象装配,具体的可以看下文档.
  如果你想拿到LocalSessionFactoryBean实例, 在id前面加个'&'就可以了,在你的配置文件中BeanFactory.getBean('&sessionFactory')拿到的就是LocalSessionFactoryBean的实例.

解决方法:

ClassPathXmlApplicationContext cpx=new ClassPathXmlApplicationContext("beans.xml");
LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)cpx.getBean("&sessionFactory");
System.out.println("step3 sessionFactory=" + sessionFactory );

 

转载于:https://www.cnblogs.com/wangshuo1/p/5598176.html

你可能感兴趣的:(org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑解决办法)