标签:
在项目中使用了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