@MapperScan和@ComponentScan一块使用导致冲突的解决

2022-07-21,,,,

目录
  • @mapperscan和@componentscan一块使用冲突
    • 解决方案
      • 方案一
      • 方案二
  • 项目中@mapperscan和@mapper共存之坑xxxmapper that could not be found.
    • 尝试解决

    @mapperscan和@componentscan一块使用冲突

    项目集成了knief4j

    报错:

    nosuchbeandefinitionexception: no qualifying bean of type 'springfox.documentation.schema.typenameextractor'

    很明显是容器缺少必须的bean,启动不成功

    解决方案

    方案一

    @mapperscan和@componentscan一起使用

    1.建一个配置类

    启动类不做改变

    package com.test.config;
    import org.springframework.context.annotation.componentscan;
    import org.springframework.context.annotation.configuration;
    
    @configuration
    @componentscan("com.test.bean")
    public class filenameutilsconfig {
    }
    

    方案二

    启动类做改变,使用@mapperscan一块扫描

    @mapperscan(basepackages = {"com.test.mapper","com.test.bean"})

    项目中@mapperscan和@mapper共存之坑xxxmapper that could not be found.

    公司项目有个小伙子将项目的日志功能做了优化。今天在pom添加依赖,在启动类上加个注解,然后启动项目突然报了modulemapper 找不到。

    项目一直是好的,又没有对这个mapper修改。进入modulemapper 中发现上面也是有@mapper注解的

    可是为什么容器找不到呢,分析一下刚刚修改的才做,引入依赖加注解,问题可能是注解上的问题,注释掉添加的注解,启动服务正常运行。罪魁祸首就是这个注解。

    点解注解发现配置类上有个@mapperscan扫描注入。发现这伙计需要操作数据库。而我接收负责的项目用的是传统的@mapper注入。

    思考:难道在一个项目中@mapperscan和@mapper不能共存吗?

    尝试解决

    自己创建一个springboot 项目,开始用@mapper 注入容器 启动程序。程序正常启动。

    停掉服务,将mapp文件上的@mapper删除 ,将文件移动到mapper文件中,在启动类上添加@mapperscan 扫包注入。正常启动。

    现在测试@mapperscan 和@mapper 分别在不包中测试一下。现在将usermapper 放在mapper包中, 将usertokenmapper 放在mapper2包中并添加@mapper 启动测试。

    启动类:

    usermapper :

    usertokenmapper :

    启动项目报错:

    description:

    field usertokenmapper in com.wyz.yangyang.member.service.impl.memberserviceimpl required a bean of type ‘com.wyz.yangyang.member.mapper2.usertokenmapper' that could not be found.

    action:

    consider defining a bean of type ‘com.wyz.yangyang.member.mapper2.usertokenmapper' in your configuration.

    disconnected from the target vm, address: ‘127.0.0.1:56527', transport: ‘socket'

    process finished with exit code 1

    然后我有测试可@mapperscan 扫描的包中不放mapper 文件,mapper2 中mapper文件都添加@mapper,发现启动正常。

    又测试了@mapperscan 和@mapper 同在一个包中,启动正常。

    在此可以看出 @mapperscan 和@mapper在不同包中,@mapper注解失效。

    为了项目快速开发,为了以后更好的兼容,我将项目改为@mapperscan 模式,因为一个注解可以配置多个包路径。

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

    《@MapperScan和@ComponentScan一块使用导致冲突的解决.doc》

    下载本文的Word格式文档,以方便收藏与打印。