Spring-Mybatis整合

1.准备

pom文件

<dependencies>
    <!-- context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
    </dependency>
    <!-- mysql -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>tca</groupId>
        <artifactId>common-log-base-slf4j-log4j2</artifactId>
        <version>1.0.0</version>
    </dependency>
    <!-- hutool -->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.3.5</version>
    </dependency>
    <!-- spring-mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    <!--MyBatis的核心jar文件-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.0</version>
    </dependency>
</dependencies>

主配置

/**
 * @author zhouan
 * @Date 2021/7/26
 */
@Configuration
public class MybatisConfig {

    /**
     * 数据源
     * @return
     * @throws PropertyVetoException
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setPassword("AI@123ai");
        dataSource.setUser("root");
        dataSource.setJdbcUrl("jdbc:mysql://172.16.19.28:3306/testjdbc");
        return dataSource;
    }
	
    /**
     * SqlSessionFactoryBean 替代了 SqlSessionFactory
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        ClassPathResource[] classPathResource = new ClassPathResource[]{new ClassPathResource("mapper/InfoMapper.xml")};
        sqlSessionFactoryBean.setMapperLocations(classPathResource);
        return sqlSessionFactoryBean;
    }
	
    /**
     * MapperScannerConfigurer --> 核心配置类
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.tca.spring.framework.learning.mybatis.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        return mapperScannerConfigurer;
    }
}

dao

public interface InfoMapper {

    /**
     * selectById
     * @param id
     * @return
     */
    Info selectById(@Param("id") Integer id);
}

mapper.xml

<mapper namespace="com.tca.spring.framework.learning.mybatis.dao.InfoMapper">

    <select id="selectById" resultType="com.tca.spring.framework.learning.mybatis.entity.Info">
        select * from info where id = #{id}
    </select>

</mapper>

entity

@Data
public class Info {

    private Integer id;

    private Integer age;

    private String name;
}

启动类

public class MybatisStarter {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MybatisConfig.class);
        InfoMapper infoMapper = applicationContext.getBean(InfoMapper.class);
        Info info = infoMapper.selectById(1);
    }
}

2.MapperScannerConfigurer

2.1 结构图

MapperScannerConfigurer结构图

我们可以看到, MapperScannerConfigurer类实现了: BeanDefinitionRegistryPostProcessor、ApplicationContextAware、BeanNameAware、InitializingBean, 这几个接口的作用:
1.BeanDefinitionRegistryPostProcessor接口, 完成bean的扫描注册, ConfigurationClassPostProcessor就是实现了这个接口, 具体作用@Spring源码中有讲解, 这里不作赘述。BeanDefinitionRegistryPostProcessor接口继承了BeanFactoryPostProcessor接口, BeanFactoryPostProcessor用于实现对BeanFactory的增强;
2.BeanNameAware实现了Aware接口, 在MapperScannerConfigurer bean的初始化的时候回调对应方法, 这个方法是属性注入完成之后, 初始化方法执行之前调用
3.ApplicationContextAware实现了Aware接口, 在第七次使用BeanPostProcessor时, 会调用ApplicationContextAwareProcessor, 回调ApplicationContextAware对应方法
4.InitializingBean接口, 也会在bean的初始化的时候回调对应方法
综上 BeanNameAware, ApplicationContextAware, InitializingBean的回调, 都是在属性注入之后, AOP完成之前进行

问题:MapperScannerConfigurer对应的bean什么时候完成初始化

1.由@spring源码我们知道, spring会先实例化ConfigurationClassPostProcessor这个bean, 它实现了BeanDefinitionRegistryPostProcessor接口和PriorityOrdered接口, 因此会优先调用它的postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)方法, 这个方法用于bean的扫描并封装成BeanDefinition; 所以此时MapperScannerConfigurer, 会被封装成BeanDefinition;
2.spring会继续找BeanDefinitionRegistryPostProcessor接口对应的所有BeanDefinition, 进行实例化, 并放入了容器中
3.调用BeanDefinitionRegistryPostProcessor实现类的 postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)方法

2.2 MapperScannerConfigurer#postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    if (this.processPropertyPlaceHolders) {
        processPropertyPlaceHolders();
    }
    // 创建ClassPathMapperScanner对象
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
    // true
    scanner.setAddToConfig(this.addToConfig);
    // null
    scanner.setAnnotationClass(this.annotationClass);
    // null
    scanner.setMarkerInterface(this.markerInterface);
    // null
    scanner.setSqlSessionFactory(this.sqlSessionFactory);
    // null
    scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
    // sqlSessionFactoryBeanName == "sqlSessionFactoryBean"
    scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
    // null
    scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
    // applicationContext
    scanner.setResourceLoader(this.applicationContext);
    // nameGenerator
    scanner.setBeanNameGenerator(this.nameGenerator);
    // 添加filter --> includeFilter 和 excludeFilter
    scanner.registerFilters();
    // basePackage == "com.tca.spring.framework.learning.mybatis.dao"
    // 它是借助了父类ClassPathBeanDefinitionScanner进行扫描
    // 这里使用了模板方法设计模式, scanner.scan(String... package)调用了父类(ClassPathBeanDefinitionScanner)的scan方法, 父类的scan方法中会调用doScan()方法, 这里scanner会重写doScan()方法
    // 见@2.3, 分析ClassPathBeanDefinitionScanner#scan(String... package)方法
    scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}

流程图

ClassPathMapperScanner

结构图 - ClassPathMapperScanner

ClassPathMapperScanner结构图

2.3 ClassPathBeanDefinitionScanner#scan(String... package)

public int scan(String... basePackages) {
    // 1.获取容器中已经有的BeanDefinition的数量, 已经有的包含三部分: 
    // 1.容器自身添加进去的
    // 2.ConfigurationClassPostProcessor扫描后创建的
    // 3.其他自定义BeanDefinitionRegistryPostProcessor扫描创建的
    int beanCountAtScanStart = this.registry.getBeanDefinitionCount();

    // 2.这里被子类 ClassPathMapperScanner 重写了, 所以调用了子类的doScan方法,  见@2.4
    doScan(basePackages);

    // Register annotation config processors, if necessary.
    if (this.includeAnnotationConfig) {
        AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }

    return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}

2.4 ClassPathMapperScanner#doScan(String... basePackages)

@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
    // 1.先调用父类的方法(太秀了), 重写了这个方法之后, 先调用父类的, 再进行增强
    // 父类的这个方法不再做解析, 见@Spring源码, 其作用是扫描包, 将包下的类创建对应的BeanDefinition, 再用BeanDefinitionHolder做一层封装并返回
    // 这里我们拿到的BeanDefinition, 是对InfoMapper的封装, beanClass属性为: com.tca.spring.framework.learning.mybatis.dao.InfoMapper
    Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);

    if (beanDefinitions.isEmpty()) {
        logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
    } else {
        // 2.处理bd, 这里是ClassPathMapperScanner所特有的部分, 见@2.5
        processBeanDefinitions(beanDefinitions);
    }

    return beanDefinitions;
}

2.5 ClassPathMapperScanner#processBeanDefinitions(Set beanDefinitions)

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitions) {
        definition = (GenericBeanDefinition) holder.getBeanDefinition();

        if (logger.isDebugEnabled()) {
            logger.debug("Creating MapperFactoryBean with name '" + holder.getBeanName() 
                         + "' and '" + definition.getBeanClassName() + "' mapperInterface");
        }

        // the mapper interface is the original class of the bean
        // but, the actual class of the bean is MapperFactoryBean
        // 1.在这里, 把InfoMapper作为constructorArgumentValues
        definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
        // 2.修改beanClass为 org.mybatis.spring.mapper.MapperFactoryBean
        definition.setBeanClass(this.mapperFactoryBean.getClass());
		// 3.添加("addToConfig", true)属性
        definition.getPropertyValues().add("addToConfig", this.addToConfig);

        boolean explicitFactoryUsed = false;
        if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
            // 4.添加("sqlSessionFactory", RuntimeBeanReference(sqlSessionFactory))
            definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
            explicitFactoryUsed = true;
        } else if (this.sqlSessionFactory != null) {
            definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
            explicitFactoryUsed = true;
        }
		
        if (StringUtils.hasText(this.sqlSessionTemplateBeanName)) {
            if (explicitFactoryUsed) {
                logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate", new RuntimeBeanReference(this.sqlSessionTemplateBeanName));
            explicitFactoryUsed = true;
        } else if (this.sqlSessionTemplate != null) {
            if (explicitFactoryUsed) {
                logger.warn("Cannot use both: sqlSessionTemplate and sqlSessionFactory together. sqlSessionFactory is ignored.");
            }
            definition.getPropertyValues().add("sqlSessionTemplate", this.sqlSessionTemplate);
            explicitFactoryUsed = true;
        }

        if (!explicitFactoryUsed) {
            if (logger.isDebugEnabled()) {
                logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
            }
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
        }
    }
}

3.MapperFactoryBean

3.1 结构图

MapperFactoryBean继承SqlSessionDaoSupport实现了InitialzingBean接口, 同时实现了FactoryBean接口
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {
    /**
     * 需要代理的接口
     */
    private Class<T> mapperInterface;

    /**
     * 此字段的作用: 如果为true, 指定的接口还没有被MyBatis解析过, 也就是说MyBatis
     * 还没有对这个接口做绑定时, 那么会去解析这个接口, 并绑定该接口。
     * 这个接口可以采用MyBatis注解的方式书写SQL, 也可以采用XML的经典方式。
     */
  	private boolean addToConfig = true;
    
    public MapperFactoryBean(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }
    
    /**
     * 此方法在afterPropertiesSet调用
     * SqlSessionDaoSupport继承了DaoSupport,而DaoSupport实现了InitializingBean接口
     */
    @Override
    protected void checkDaoConfig() {
        // 父类SqlSessionDaoSupport会检查SqlSession是不是null
        super.checkDaoConfig();
		// 检查接口
        notNull(this.mapperInterface, "Property 'mapperInterface' is required");

        Configuration configuration = getSqlSession().getConfiguration();
        // 如果这个接口还没有被MyBatis解析过, 那么解析这个接口
        // addMapper会解析MyBatis注解方式, 同时还会搜寻同包同名的XML映射文件完成绑定
        if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
            try {
                configuration.addMapper(this.mapperInterface);
            } catch (Exception e) {
                logger.error("Error while adding the mapper '" + 
                             this.mapperInterface + "' to configuration.", e);
                throw new IllegalArgumentException(e);
            } finally {
                ErrorContext.instance().reset();
            }
        }
    }

    /**
     * 返回一个接口的代理实现
     */
    @Override
    public T getObject() throws Exception {
        return getSqlSession().getMapper(this.mapperInterface);
    }

    @Override
    public Class<T> getObjectType() {
        return this.mapperInterface;
    }
    
    @Override
    public boolean isSingleton() {
        return true;
    }
}

4.SqlSessionFactoryBean

4.1 结构图

SqlSessionFactoryBean结构图

可以看到, SqlSessionFactoryBean实现了 FactoryBean接口和 InitializingBean接口

4.2 作用

1.我们在主配置类MyBatisConfig中, 创建了SqlSessionFactoryBean, 并将它交给了Spring容器, 同时我们创建了MapperScannerConfigurer, 并将SqlSessionFactoryBean的引用作为了MapperScannerConfigurer的成员变量
2.SqlSessionFactoryBean是一个FactoryBean, 因此它主要的作用是getObject()返回对象, 即返回SqlSessionFactory对象, 这是mybatis中创建sqlSession的核心类, SqlSession负责创建Mapper的代理对象
3.因为SqlSessionFactoryBean实现了 InitializingBean接口, 因此在bean的实例化过程中, 会调用其afterPropertiesSet(), 在这个方法中会创建SqlSessionFactory对象, 并存储到sqlSessionFactory实例变量中, 是一个单例
4.在getObject()方法中, 我们会将上述创建的SqlSessionFactory对象返回

5.总结

总结一下mybatis整合spring的原理

1.在主配置类中, 我们向容器中注入了两个bean: SqlSessionFactoryBean 和 MapperScannerConfigurer, 其中MapperScannerConfigurer引用了SqlSessionFactoryBean, SqlSessionFactoryBean用于实例化SqlSessionFactory
2.MapperScannerConfigurer是一个BeanDefinitionRegistryPostProcessor, 它用于自定义扫描包, 它创建了ClassPathMapperScanner用于扫描, 它会扫描我们传入的Mapper的类所在的basePackage, 取出所有Mapper接口, 封装成BeanDefinition, 默认情况下, BeanDefinition对应的beanClass属性为Mapper的Class对象, 但是在这里, ClassPathMapperScanner会将beanDefinition中的beanClass从Mapper接口替换成了org.mybatis.spring.mapper.MapperFactoryBean, 同时添加了属性:
("addToConfig", true) 和 ("sqlSessionFactory", RuntimeBeanReference(sqlSessionFactory))
3.综上, 我们向容器中注入了MapperScannerConfigurer这个bean, 这个bean会扫描Mapper接口, 创建bd, 将bd的beanClass替换成MapperFactoryBean, 同时bd中包含了对SqlSessionFactoryBean的引用, SqlSessionFactoryBean可以创建SqlSessionFactory对象, 这样就可以使用 MapperFactoryBean和qlSessionFactory创建Mapper的代理对象了

5.1 问题:definition.getPropertyValues().add(key, value)到底有什么用?

1.我们看到, 这里创建的BeanDefinition, 我们把beanClass属性替换成了MapperFactoryBean之后, 我们知道后面我们会根据MapperFactoryBean创建MapperFactoryBean对象, 并且MapperFactoryBean是一个FactoryBean, 所以后面我们根据"infoMapper"这个name可以直接获取MapperFactoryBean的getObject()获取的对象, 而这里getObject()就是获取Mapper的代理对象用的;
2.但是MapperFactoryBean创建代理对象会用到一些"原料", 其中最核心的原料就是: SqlSessionFactory(这里我们用的SqlSessionFactoryBean) 以及 对应的接口Class, 即InfoMapper.class,
所以, 我们将SqlSessionFactory 和 Class<T> 作为 MapperFactoryBean的一个成员变量, 通过见@5.2
definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); 
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
这两种方式, 因此, 在创建MapperFactoryBean对象时, 会进行属性赋值!

6.@MapperScan

6.1 准备

主配置

/**
 * @author zhoua
 * @Date 2021/7/28
 */
@MapperScan(basePackages = "com.tca.spring.framework.learning.mybatis.dao",
            sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class AnnotationMybatisConfig {

    /**
     * 数据源
     * @return
     * @throws PropertyVetoException
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db_test?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf-8");
        dataSource.setUser("root");
        dataSource.setPassword("admin");
        return dataSource;
    }

    /**
     * SqlSessionFactoryBean 替代了 SqlSessionFactory
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        ClassPathResource[] classPathResource = new ClassPathResource[]{new ClassPathResource("mapper/InfoMapper.xml")};
        sqlSessionFactoryBean.setMapperLocations(classPathResource);
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}
我们看到, 其他的都一样, 主配置这里我们用@MapperScan注解代替了MapperScannerConfigurer的注入, 下面来解析@MapperScan是如何发挥作用的

6.2 代码

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
public @interface MapperScan {

    String[] value() default {};
   
    String[] basePackages() default {};

    Class<?>[] basePackageClasses() default {};

    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    Class<? extends Annotation> annotationClass() default Annotation.class;

    Class<?> markerInterface() default Class.class;

    String sqlSessionTemplateRef() default "";
   
    String sqlSessionFactoryRef() default "";

    Class<? extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;
}
可以看出, @MapperScan注解中属性值跟MapperScannerConfigurer中的属性基本一致, nameGenerator属性有默认值 BeanNameGenerator.class, factoryBean属性有默认值 MapperFactoryBean.class,
还有一个重要的属性 sqlSessionFactoryRef, 这个需要我们手动赋值

6.3 MapperScannerRegistrar

MapperScan中主要使用@Import引用了MapperScannerRegistrar

6.3.1 结构图

MapperScannerRegistrar结构图

从结构图中可以看出, MapperScannerRegistrar实现了ImportBeanDefinitionRegistrar接口, 这个接口用于向spring容器中注入自定义的BeanDefinition; 熟悉@Spring aop源码和@Spring transaction源码, 应该知道:
1.@Spring aop源码中, 开启了@EnableAspectJAutoProxy注解, 这个注解中@Import(AspectJAutoProxyRegistrar.class), 即向容器中注入了AspectJAutoProxyRegistrar, 这个类也实现了ImportBeanDefinitionRegistrar接口, 在ConfigurationClassPostProcessor扫描主配置类的解析过程中, 会创建实现了ImportBeanDefinitionRegistrar接口的实现类, 所以创建了AspectJAutoProxyRegistrar对象, 调用了其registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法, 在这个方法中向容器中注入了
AnnotationAwareAspectJAutoProxyCreator这个bean, 这个bean是真正完成aop操作的bean
2.@Spring transaction中, 开启了@EnableTransactionManagement注解, 这个注解中@Import(TransactionManagementConfigurationSelector.class), 即向容器中注入了TransactionManagementConfigurationSelector, 这是一个ImportSelector接口的实现类, 所以会调用它的selectImports(AdviceMode adviceMode)方法, 向容器中注入了两个bean: AutoProxyRegistrar和ProxyTransactionManagementConfiguration, 其中AutoProxyRegistrar也是一个ImportBeanDefinitionRegistrar接口的实现类, 因而也会创建对象, 并调用它的registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法, 向容器中注册了InfrastructureAdvisorAutoProxyCreator这个bean, 用来完成aop代理操作

综上, 我们在ConfigurationClassPostProcessor进行扫描操作时, 也会创建MapperScannerRegistrar对象, 并调用其registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法

6.3.2 MapperScannerRegistrar#registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)

public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
	// 1.获取@MapperScan注解的属性, importingClassMetadata中已经包含了@MapperScan注解的属性
    AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
    // 2.创建ClassPathMapperScanner, 并扫描, 这里跟MapperScannerConfigurer#postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)的实现几乎一致
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);

    // this check is needed in Spring 3.1
    if (resourceLoader != null) {
        scanner.setResourceLoader(resourceLoader);
    }

    Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
    if (!Annotation.class.equals(annotationClass)) {
        scanner.setAnnotationClass(annotationClass);
    }

    Class<?> markerInterface = annoAttrs.getClass("markerInterface");
    if (!Class.class.equals(markerInterface)) {
        scanner.setMarkerInterface(markerInterface);
    }

    Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
    if (!BeanNameGenerator.class.equals(generatorClass)) {
        scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass));
    }

    Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
    if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
        scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass));
    }

    scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));
    scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));

    List<String> basePackages = new ArrayList<String>();
    for (String pkg : annoAttrs.getStringArray("value")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    for (String pkg : annoAttrs.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {
        basePackages.add(ClassUtils.getPackageName(clazz));
    }
    scanner.registerFilters();
    scanner.doScan(StringUtils.toStringArray(basePackages));
}