springboot无法找到mapper的问题

953 阅读1分钟

程序启动报错:

Error creating bean with name 'appServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.boao.workflow.mapper.base.IAppMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

服务类appServiceImpl找不到依赖的IAppMapper,应该是没有扫描mapper接口.

IAppMapper使用@Repository标记

@Repository
public interface IAppMapper extends BaseMapper<App> {
    List<App> selectAppList();
}

解决方法:

  1. 在启动类上添加@MapperScan,并指定包名
@MapperScan(basePackages = {"com.xxx.*.mapper.*"})
public class ManagerApplication {}

另外这个@MapperScan也可以放到配置类上,比如

@Configuration
@MapperScan("com.xxx.*.mapper.*")
public class MybatisPlusConfig {}

这种情况适用于模块依赖的情况,比如mapper接口在A.jar中,B依赖A.jar,那么接口的扫描放到A模块中比较好,即将@MapperScan放到A模块的配置类中。

  1. 在mapper接口上添加@Mapper,替换掉@Repository

小结:

  1. @Mapper和@ScanMapper选择一种方式使用即可,一个标注到每个接口类上,一个只需要标注到启动类上
  2. 在某些场合适合将@ScanMapper加到配置类上(带有@Configuration注解的为配置类)

另,@Mapper和@Repository区别:

  1. @Repository 是Spring的注解,用来标识一个Spring Bean,主要用来标注dao类,在springboot中会自动扫描@Mapper注解,spring中需要配置MapperScannerConfigurer
  2. @Mapper 是mybatis的注解,与spring整合时mybatis需要使用@Mapper找到自己的mapper接口,如果不想在每个Mapper类上都加注解,可以在启动类或配置类上添加@MapperScan("包路径")

mybatisplus-boot-starter中自动扫描代码: mybatisplus-boot-starter.png