本文基于mybatis-spring 1.3.1和mybatis 3.4.4版本
注解MapperScan是mybatis的核心注解,它可以设置Mapper文件的扫描路径。本文将详细介绍该注解以及各个属性作用。
@MapperScan放在spring boot可以扫描到的位置即可,一个应用配置一个该注解,比如:
@MapperScan(basePackages="com.parser.db") @SpringBootApplication(scanBasePackages={"com.parser"}) public class Main { public static void main(String[] args) throws Exception { // 创建spring容器 ApplicationContext context =new SpringApplicationBuilder(Main.class) .web(WebApplicationType.NONE).bannerMode(Banner.Mode.OFF) .run(args); } }注解MapperScan还引入了类MapperScannerRegistrar。 MapperScannerRegistrar实现了接口ImportBeanDefinitionRegistrar,所以在spring容器启动的时候,该类就会被执行。 该类的作用是扫描指定包路径下的Mapper接口,并且对接口进行过滤,接口必须符合annotationClass和markerInterface指定的内容。找到所有的接口后,对每个接口创建对应的BeanDefinition对象,并将factoryBean指定的MapperFactoryBean设置到BeanDefinition中,然后将BeanDefinition注册到spring容器中,spring容器接下来会使用MapperFactoryBean创建Mapper对象。
