码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-06-19 17:00:50      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="hibernateProperties">
  <props>
  <prop key="hibernate.dialect" >org.hibernate.dialect.SQLServerDialect</prop>
  <prop key="hibernate.jdbc.batch_size">20</prop>
  <prop key="hibernate.show_sql">true</prop>
  </props>
  </property>
  <property name="mappingResources">
  <list>
  <value>com/jw/pojo/JwUser.hbm.xml</value>
  </list>
  </property>
  </bean>

在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 );

 

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

标签:

原文地址:http://www.cnblogs.com/wangshuo1/p/5598176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!