spring,mybatis源码深度解析
Mybatis整合spring,主要通过两种途径:一种是基于xml配置的,一种基于java config 配置。
一种是基于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操作数据库了。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。