Mybatis-Spring:MapperScan

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Spring:MapperScan相关的知识,希望对你有一定的参考价值。

参考技术A 环境:mybatis-spring 2.0.3

通常使用Mybatis集成Spring,会使用 @MapperScan 指定接口扫描路径

@MapperScan 使用了Spring元注解 @Import 向Spring容器注册了 MapperScannerRegistrar

MapperScannerRegistrar 实现了Spring的 ImportBeanDefinitionRegistrar 接口,会在Spring处理使用 @Configuration 注解的时候向添加额外的 BeanDefinition ,要结合 @Import 使用,通过它最终向Spring容器注册了 MapperScannerConfigurer 类

再来看 MapperScannerConfigurer ,为什么要向Spring注册这个类?

它实现了 BeanDefinitionRegistryPostProcessor 接口,能够在Spring的 BeanFactoryPostProcessor 介入之前注册更多的 BeanDefinition ,通过这个接口,Mybatis实现了自己的 ClassPathMapperScanner ,通过这个类扫描注册自己的Mapper接口定义

ClassPathMapperScanner 继承了 ClassPathBeanDefinitionScanner ,重写了父类的 doScan 方法

父类 ClassPathBeanDefinitionScanner 提供了扫描路径方法 scan

子类 ClassPathMapperScanner 重写的 doScan 方法

至此,Mybatis集成Spring已经完成了将Mapper接口改造的 BeanDefinition 注册到Spring,后续只需要Spring根据 MapperFactoryBean 的 getObject 方法就能够回去接口实现类即可实现接口代理对象注入

以上是关于Mybatis-Spring:MapperScan的主要内容,如果未能解决你的问题,请参考以下文章

@MapperScan与@Mapper

@MapperScan与@Mapper

@MapperScan使用

@mapperscan 注解啥时候起作用

@MapperScan注解

@MapperScan注解