spring,mybatis源码深度解析

Mybatis整合spring,主要通过两种途径:一种是基于xml配置的,一种基于java config 配置。

河南网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设公司等网站项目制作,到程序开发,运营维护。创新互联公司2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联

  • 一种是基于xml配置的。这种方式通过解析xml,生成bean。主要是通过扩展spirng NamespaceHandlerSupport类型来实现自定义解析Mybatis的xml配置。Mybatis相关实现主要提现的类NamespaceHandler、MapperScannerBeanDefinitionParser。

  • 一种基于java config 配置。这种方式通过注解MapperScan,让spring容器扫描到注解。Mybatis相关实现主要体现的类:注解@interface  MapperScan、MapperScannerRegistrar。


        这两种方法的实现都是通过Mybatis的ClassPathMapperScanner类向容器中注册bean的。

        那这个ClassPathMapperScanner扫描到Mybatis的mapper接口,是如何注册实例的呢,接口又怎么会实例呢。关键代码处

?

1

2

3

4

  // the mapper interface is the original class of the bean

        // but, the actual class of the bean is MapperFactoryBean

        definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());

        definition.setBeanClass(MapperFactoryBean.class);

    其实是通过更改注册容器中bean的beanClass属性为MapperFactoryBean(工厂bean)生成实例的。容易中注册的bean其实是工厂bean,spring中的工厂bean获得实例是调用工厂方法获得。

MapperFactoryBean的功能是:

/**

 * BeanFactory that enables injection of MyBatis mapper interfaces. It can be set up with a

 * SqlSessionFactory or a pre-configured SqlSessionTemplate.

看一下这个spring工厂bean生成实例的最主要代码: 

?

1

2

3

public T getObject() throws Exception {

    return getSqlSession().getMapper(this.mapperInterface);

  }

 生成实例的时候,通过这个函数整合到了mybatis操作数据库的接口。

剩下的那就是mybatis操作数据库了。


新闻标题:spring,mybatis源码深度解析
当前网址:http://pwwzsj.com/article/gcehoo.html