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

 更新时间:2021年11月6日 00:01  点击:1793 作者:三人行必有吾师焉

@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 模式,因为一个注解可以配置多个包路径。

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

原文出处:https://blog.csdn.net/qq_42907029/article/details/117126360

[!--infotagslink--]

相关文章

  • mybatis注解之@Mapper和@MapperScan的使用

    这篇文章主要介绍了mybatis注解之@Mapper和@MapperScan的使用,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-09
  • @MapperScan和@ComponentScan一块使用导致冲突的解决

    这篇文章主要介绍了@MapperScan和@ComponentScan一块使用导致冲突的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-11-06