【已解决】关于Mapper接口、service接口注入失败原因

背景:

    1、使用maven分模块构建SSM工程 2、没有mybatis映射文件和核心配置文件 3、(2)中的配置都在spring配置中

错误信息

Error creating bean with name mainController: Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name userServiceImpl: Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type com.seig.mapper.UserMapper available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {
          
   @javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}

文字说明:一直提示userMapper这个接口注入失败。

疑惑: 鄙人的配置跟视频一样,跟上一次项目配置也一样,为什么还报错?

怎么办?

问度娘:

    1、你web.xml中没有配置监听器加载spring配置文件
【有道理】。不加载spring配置文件,等于没有使用spring,而mybatis靠spring整合,所有mybatis也等于没效果
<!-- 配置spring的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
    2、你接口没有加@Mapper和@MapperScan注解
【但我没给mapper接口加注解也可以😂】 听听看: mybatis-config中只是会为对应的mapper创建代理类,而想真正包装成bean,注入到spring容器中,还是需要靠AutoConfiguredMapperScannerRegistrar,它会根据扫描@Mapper注释或是@MapperScan指定的包下的接口,将其注册为bean。
    3、你没有配置接口实现bean
这个是假答案。我spring帮我生成mapper接口的动态代理对象,我还配置个毛线

我设置context-param全局参数用来解析applicationContext.xml启用spring容器,但不需要加@Mapper和@MapperScan注解,也不需要什么配置mybatis映射文件和mybatis核心配置文件(因为我使用注解)。

原来是我犯了第一条错误,因为忘记在web.xml中没有配置监听器加载spring配置文件,不加载spring配置文件,等于没有使用spring,而mybatis靠spring整合,所有mybatis也等于没效果。

经验分享 程序员 微信小程序 职场和发展