Mybatis解析-注解MapperScan详解

    科技2026-01-15  13

    本文基于mybatis-spring 1.3.1和mybatis 3.4.4版本

    注解MapperScan是mybatis的核心注解,它可以设置Mapper文件的扫描路径。本文将详细介绍该注解以及各个属性作用。

    文章目录

    一、如何使用注解MapperScan二、MapperScan各个属性介绍三、MapperScannerRegistrar

    一、如何使用注解MapperScan

    @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各个属性介绍

    //与basePackages作用一样 String[] value() default {}; //定义Mapper接口的扫描路径,可以定义多个,中间用逗号分隔 //mybatis只扫描接口,而且接口至少有一个方法,类不扫描 String[] basePackages() default {}; //与basePackages类似, //mybatis获取配置的类的包路径,该包路径就是mybatis扫描接口的路径 Class<?>[] basePackageClasses() default {}; //名字产生器, //mybatis对扫描到的每个Mapper接口文件会创建对应的Bean对象, //BeanNameGenerator用于生成Bean对象的名字 //默认是AnnotationBeanNameGenerator,其产生的名字是接口名首字母小写 Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class; //如果定义了annotationClass,mybatis只扫描有指定注解的Mapper接口, //这个注解可以直接注解在Mapper接口上,也可以是元注解 Class<? extends Annotation> annotationClass() default Annotation.class; //与annotationClass类似,只不过markerInterface用于设置接口, //扫描的Mapper接口需要继承指定接口或者自身就是指定的接口 Class<?> markerInterface() default Class.class; //指定一个SqlSessionTemplate对象,当spring容器中有多个时,需要指定 String sqlSessionTemplateRef() default ""; //指定一个SqlSessionFactory对象,当spring容器中有多个时,需要指定 String sqlSessionFactoryRef() default ""; //指定自定义的MapperFactoryBean,MapperFactoryBean实现FactoryBean接口, //每个Mapper对象都是MapperFactoryBean生成的 Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;

    三、MapperScannerRegistrar

    注解MapperScan还引入了类MapperScannerRegistrar。 MapperScannerRegistrar实现了接口ImportBeanDefinitionRegistrar,所以在spring容器启动的时候,该类就会被执行。 该类的作用是扫描指定包路径下的Mapper接口,并且对接口进行过滤,接口必须符合annotationClass和markerInterface指定的内容。找到所有的接口后,对每个接口创建对应的BeanDefinition对象,并将factoryBean指定的MapperFactoryBean设置到BeanDefinition中,然后将BeanDefinition注册到spring容器中,spring容器接下来会使用MapperFactoryBean创建Mapper对象。

    Processed: 0.023, SQL: 9