在学习myBatis持久层框架时,通常遇到一些挫折,下面我遇到一个错让我头疼了两周,但最后的解决方案却十分简单,下面就让我说说
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.lin.test.dao.UserDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 41 more
当出现上述错误时,有两种可能,第一种可能是你的映射文件写错,一对一,一对多关系配置出问题,这也是大多新手学习myBatis时遇到的问题,有需要的可以访问这个链接“http://www.mybatis.org/mybatis-3/zh/index.html”,里面有MyBatis的详细介绍。
第二种可能就是没有扫描接口所在的包,映射所在的包,实体所在的包。
applicationContext.xml配置
<!-- 包扫描 -->
<!-- 连接池配置。。。 -->
<!-- 配置session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" scope="singleton">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="typeAliasesPackage" value="cn.lin.test.entity"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:cn/lin/test/mapper/*.xml"/>
</bean>
<!-- 扫描接口包 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.lin.test.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 事务配置。。。 -->
mybatis-config.xml配置
<configuration>
<settings>
<!-- 使用jdbc的getGeneratedKeys 获取数据库自增主键值 -->
<setting name="useGeneratedKeys" value="true"/>
<!-- 使用列别名替换列名 默认:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 全局懒加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启驼峰命名转换:Table{create_time} 》 Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
我的错误解决方法是:
添加“org.mybatis.spring.mapper.MapperScannerConfigurer”bean的配置,里面配置接口扫描!问题就这样解决
可以帮助到你的请给我点赞,谢谢!
感兴趣的朋友可以关注微信公众号(会定时推送新的知识):