MyBatis可以独立于Spring使用,这里我们关注一下Mybatis和Spring是怎么整合在一起的。在Spring中使用MyBatis时我们只需要定义一个mapper接口,并配置好对应的mapper.xml,这样就可以直接通过mapper接口直接执行数据库操作。但是我们并没有手动的实例化该接口,那它是如何进行实例化并加入spring容器的呢?
配置文件入手
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="mysql" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<!--连接池启动时的初始值-->
<property name="initialSize" value="1"></property>
<!--连接池的最大值-->
<property name="maxActive" value="300"></property>
<!--最大空闲值,当经过一个高峰时间后,连接池可以慢慢的将已经用不到的连接慢慢的释放一部分,一直减少到maxIdle为止-->
<property name="maxIdle" value="2"/>
<!--最小空闲值,当空闲的连接数减到小于阈值时,连接池就会去预申请一些连接,以免洪峰来时来不及申请-->
<property name="minIdle" value="1"/>
<property name="maxWait" value="500"/>
<property name="defaultAutoCommit" value="true"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="${dbType}"/>
<property name="configLocation" value="classpath:mybatis-spring-config.xml"/>
</bean>
<!--单个映射器-->
<!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.excelib.dao.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>-->
<!--扫描映射器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.excelib.dao"></property>
</bean>
</beans>
MapperScannerConfigurer
与Spring整合的时候配置了两个类org.mybatis.spring.SqlSessionFactoryBean
、org.mybatis.spring.mapper.MapperScannerConfigurer
。
SqlSessionFactoryBean的对mapper.xml的处理可以参考【MyBatis】mapper.xml解析及annotation支持源码分析,下面分析一下MapperScannerConfigurer到底做了些什么。
由上图可以看出这个类实际上实现了几个Spring的接口。查看他的实现的方法,似乎只有postProcessBeanDefinitionRegistry()
里有我们关心的内容,这个方法会在BeanDefinition注册后调用,这是还没有创建bean的实例。
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
//提前处理PropertyPlaceHolder
processPropertyPlaceHolders();
}
//创建一个ClassPathMapperScanner对象,配置扫描包、sqlSessionFactory等
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
//调用父类注册过滤器,只扫描指定的类
scanner.registerFilters();
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
@Override
public void afterPropertiesSet() throws Exception {
notNull(this.basePackage, "Property 'basePackage' is required");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* {@inheritDoc}
*/
@Override
public void setBeanName(String name) {
this.beanName = name;
}
postProcessBeanDefinitionRegistry()
中的大致逻辑是创建一个ClassPathMapperScanner对象,调用父类ClassPathBeanDefinitionScanner.scan()
(ClassPathBeanDefinitionScanner
是Spring中的对象)其中会调用ClassPathBeanDefinitionScanner.doScan()
方法来扫描我们配置的package,并封装成beanDefinition加入Spring容器,并返回所有扫描到的beanDefinition。由于子类ClassPathMapperScanner重写了doScan方法,所以最终会调用ClassPathMapperScanner.doScan();
ClassPathMapperScanner
ClassPathMapperScanner.doScan
调用父类的doScan方法(扫描我们配置的package,并封装成beanDefinition加入Spring容器)然后调用processBeanDefinitions处理beanDefinitions,处理过程包含如下几个方面:
- beanDefinition中保存了bean的构造方法参数ConstructorArgumentValues,在构造方法参数新增传入原mapper接口
- 将beanDefinition的BeanClass属性统一改为org.mybatis.spring.mapper.MapperFactoryBean
- 将beanDefinition的属性新增sqlSessionFactory或者sqlSessionTemplate
//org.mybatis.spring.mapper.ClassPathMapperScanner#doScan
@Override
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
//所有扫描到的BeanDefinitionHolder放入beanDefinitions集合中
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 {
//统一处理扫描到的beanDefinitions
processBeanDefinitions(beanDefinitions);
}
return 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
//definition中保存的构造方法参数传入原mapper的类名
definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59
//definition的class全部统一为MapperFactoryBean.class
definition.setBeanClass(this.mapperFactoryBean.getClass());
definition.getPropertyValues().add("addToConfig", this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory", new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionFactory != null) {
//传入sqlSessionFactory
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);
}
}
}
MapperFactoryBean
我们可以思考下通过这些处理以后对Spring容器实例化这些扫描到的bean有什么影响?
- 首先Spring会使用beanDefinition的beanClass创建实例,这里的beanClass是
org.mybatis.spring.mapper.MapperFactoryBean
,所以会创建一个MapperFactoryBean对象,而且在调用构造方法创建它的时候会传入构造方法参数ConstructorArgumentValues,即传入mapper的接口。MapperFactoryBean.mapperInterface就是扫描到的mapper接口
public MapperFactoryBean(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
- 我们由类图还发现MapperFactoryBean这个类实现了FactoryBean接口,Spring会调用
FactoryBean.getObeject
来获取真实的bean并注册到容器中,所以这里真实注册的bean应该是getSqlSession().getMapper(this.mapperInterface);
获取到的对象。
/**
* {@inheritDoc}
*/
@Override
public T getObject() throws Exception {
return getSqlSession().getMapper(this.mapperInterface);
}
MapperFactoryBean继承自SqlSessionDaoSupport,所以getSqlSession其实是调用父类的方法。在父类初始化sqlSessionFactory的时候创建sqlSession即this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
//public abstract class SqlSessionDaoSupport extends DaoSupport {
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
if (!this.externalSqlSession) {
this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
}
}
public SqlSession getSqlSession() {
return this.sqlSession;
}
}
SqlSessionTemplate.getMapper
SqlSessionTemplate.getMapper-》Configuration.getMapper-》mapperRegistry.getMapper
//org.mybatis.spring.SqlSessionTemplate#getMapper
@Override
public <T> T getMapper(Class<T> type) {
return getConfiguration().getMapper(type, this);
}
public class Configuration {
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
}
public class MapperRegistry {
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
knownMappers.put(type, new MapperProxyFactory<T>(type));
// It's important that the type is added before the parser is run
// otherwise the binding may automatically be attempted by the
// mapper parser. If the type is already known, it won't try.
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
}
MapperRegistry.getMapper会从knownMappers取,addMapper的时候会往knownMappers里加数据,而addMapper的则是在Mybatis的xml解析及注解支持那部分调用的(可以参考【MyBatis】mapper.xml解析及annotation支持源码分析),每一个mapperInterface对应一个MapperProxyFactory,取出的对象是对应的mapperProxyFactory;
MapperProxyFactory
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy)
最终产生动态代理代码中代理接口就是mapperInterface,而InvocationHandler是mapperProxy。我们调用mapper接口方法的时候其实会调用到mapperProxy.invoke
,这部分在后面分析Sql执行流程的时候再来分析。
至此扫描配置的包路径下所有mapper接口都会通过getSqlSession().getMapper(this.mapperInterface);
生成一个bean注册到Spring容器中。所以通过@Autowired 等注解注入的mapper接口的实例其实就是通过getSqlSession().getMapper(this.mapperInterface);
生成的一个代理对象,调用这个代理对象执行数据库操作的时候会调用mapperProxy.invoke