spring中mapper注入的问题!!!一定要仔细细心,避坑!!!
作者:mmseoamin日期:2023-12-18

mapper注入所遇到的坑

今天在写项目的时候新建了一个模块,建了新的mapper,controller,service包,在写完代码进行测试的时候报了mapper找不到的错误

截图如下:

spring中mapper注入的问题!!!一定要仔细细心,避坑!!!,在这里插入图片描述,第1张

我心想,这报错我熟啊,不就是找不到bean吗,应该是我哪里忘了加注解了,类没有注册到spring容器中,然后我就去排错了

错误提示中有一句:

No qualifying bean of type 'com.valentin.wechat.mapper.WechatMenuMapper' available

思路一下子就清晰了,mapper没有注入,于是我找到mapper类加上了注解(我这里使用的MabatisPlus)

spring中mapper注入的问题!!!一定要仔细细心,避坑!!!,在这里插入图片描述,第2张

心想这肯定没问题了吧,于是我点击了运行,结果还是找不到这个bean

我:???

嗷~我明白了spring扫描包的问题,我又去检查了一下之前配置的application.yaml

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 查看日志
  mapper-locations: classpath:com/valentin/*/mapper/xml/*.xml  #mapper路径的位置

很好啊,不需要改啊,这里/mapper/前面的*已经把我新建包的结构包括进去了呀,是扫描这些包下的没错啊

当我找了半天没找到的时候我想起来了mapperscan这个注解,之前一直没往这方面想,因为我的mapperscan之前是加在了启动类上,后来转移到mybatisplus配置类上了,我就给忘记了

@Configuration
@MapperScan(basePackages = {"com.valentin.auth.mapper","com.valentin.process.mapper","com.valentin.wechat.mapper"})
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置
     * MybatisConfiguration#useDeprecatedExecutor = false
     * 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

还有就是写代码一定要细心,这样的小问题耽误太多的时间实在是太不应该了,写篇博客引以为戒

之后我把application.yaml中的mapper包的位置注释掉了之后没有报错也运行起来了,只是会有一个警告,提示mapper的路径没有配置

spring中mapper注入的问题!!!一定要仔细细心,避坑!!!,在这里插入图片描述,第3张

但是如果我把mapperscan给注释掉只留下yaml中的配置,运行就会找不到mapper

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 查看日志
  mapper-locations: classpath:com/valentin/*/mapper/xml/*.xml  #mapper路径的位置

是我yaml的mapper路径写错了吗,还是说这个配置并不是这么用的,有没有路过的大神给我解答一下