Spring MVC 启动时出现如下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XXX': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected XXXDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [XXXDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
主要是解析bean错误,可能时写代码时拼写错误,还有一种可能就是xml配置文件错误,尤其时spring搜索注解时的配置。
下面时配置两个跨包注解引用的例子,注意通配符的使用:
<!-- MyBatis配置 -->
<bean id="mysqlSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉xml里的手工配置 -->
<!-- 分别扫描com.xx.entity和com.yy.*.entity包的entity -->
<!-- 其中com.yy.*.entity,可以扫描类似com.yy.AAA.entity和com.yy.BBB.entity等不同子项目的entity -->
<!-- 一开始以为时这样配置 com.yy..entity 时从aop中迁移过来的错误看法-->
<property name="typeAliasesPackage" value="com.xx.entity;com.yy.*.entity" />
<!-- 显式指定Mapper文件位置 -->
<property name="mapperLocations">
<list>
<!-- 扫描mybatis目录下两层目录中带Mapper.xml的文件-->
<value>classpath:/mybatis/**/**/*Mapper.xml</value>
</list>
</property>
<property name="plugins">
<array>
<ref bean="pagePlugin" />
</array>
</property>
</bean>
<!-- 扫描basePackage下所有以@Repository标识的 接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="mysqlSqlSessionFactory" />
<!-- 多个包用分号(;)隔开,如果有规律可以用通配符 -->
<!-- 分别扫描com.xx.repository中的dao和com.yy.*.repository中的dao -->
<!-- 其中com.yy.*.repository可以扫描类似com.yy.AA.repository和com.yy.BB.repository等目录下的dao -->
<property name="basePackage" value="com.xx.repository;com.yy.*.repository" />
<!-- 优化速度 -->
<property name="annotationClass" value="com.xx.repository.base.xxBatis" />
</bean>