在spring中使用SqlSessionTemplate注入sqlsession时报错:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.apache.ibatis.session.SqlSession com.hsk.ssm.demo.service.AccountServiceImpl.sqlSession; nested exception is java.lang.NoClassDefFoundError: org/apache/ibatis/cursor/Cursor
spring配置如下:
<!-- 注入sqlSessionFactory spring集成mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="configLocation" value="classpath:mybatis.xml"></property> -->
<property name="mapperLocations" value="classpath:com/hsk/ssm/demo/mapper/*.xml"></property>
</bean>
<!-- 直接通过SqlSessionTemplate来构造注入sqlsession无需在通过sqlsessionfacoty来opensession了 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
mybatis和mybatis-spring依赖如下
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
原因:
mybatis的3.4.0及以上版本只支持mybatis-spring1.3.0及以上版本,mybatis的3.4.0以下版本用mybatis-spring1.3.0以下版本。
所以将mybatis-spring的依赖版本调整到1.3.0一下比如1.2.5就可以了。