MybatisAutoConfiguration是mybatis在springboot下自动配置类,该配置类向spring容器注入了SqlSessionFactory和SqlSessionTemplate,注入的SqlSessionFactory是通过SqlSessionFactoryBean的getObject()获取到的。SqlSessionFactoryBean通过buildSqlSessionFactory()创建SqlSessionFactory时,会通过MapperRegistry添加mapper,源码如下:
public void addMapper(Class 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(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);
}
}
}
}
可以看出在添加mapper时,会将mapper包装成MapperProxyFactory类。MapperRegistry同时提供了getMapper
public T getMapper(Class type, SqlSession sqlSession) {
final MapperProxyFactory mapperProxyFactory = (MapperProxyFactory) 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);
}
}
在获取mapper时,先获取到的是MapperProxyFactory包装类,然后通过MapperProxyFactory的newInstance获取最终的mapper对象。
protected T newInstance(MapperProxy mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy mapperProxy = new MapperProxy(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
从上面源码可以看出,最终返回的是一个由jdk动态代理生成的对象,如图所示(这是mybatisplus生成的代理对象)所以mapper接口中的所有方法最终都是通过MapperProxy的invoke方法执行。我们给其他spring管理的bean注入的mapper就是这个代理对象。
那么getMapper又是如何调用的呢?
在spring创建mapper对象时,通过createbean方法创建出来的bean是一个MapperFactoryBean对象,spring通过调用MapperFactoryBean的getObject()获取最终需要的bean对象,而这时就会调用MapperRegistry的getMapper方法。
那么为什么所有的mapper获取出来的bean都是MapperFactoryBean对象呢?这就得从bean定义说起。下面通过@MapperScan简单说下。
@Import(MapperScannerRegistrar.class)
public @interface MapperScan
MapperScan定义了扫描mapper接口的路径,MapperScannerRegistrar实现了ImportBeanDefinitionRegistrar接口,该接口是spring对于bean定义的一个扩展接口,spring data也是通过实现该接口处理repository等的定义与生成的。
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes mapperScanAttrs = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
if (mapperScanAttrs != null) {
registerBeanDefinitions(mapperScanAttrs, registry);
}
}
void registerBeanDefinitions(AnnotationAttributes annoAttrs, BeanDefinitionRegistry registry) {
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
mybatis通过ClassPathMapperScanner去扫描MapperScan定义的包路径,ClassPathMapperScanner 继承了ClassPathBeanDefinitionScanner,ClassPathMapperScanner先通过ClassPathBeanDefinitionScanner扫描(在指定的基本包中执行扫描,返回注册的bean定义),然后通过processBeanDefinitions方法将bean定义的beanClass修改成了MapperFactoryBean,spring通过bean定义生成bean对象时就会生成MapperFactoryBean对象。源码如下:
private void processBeanDefinitions(Set beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
...
definition.setBeanClass(this.mapperFactoryBean.getClass());
@Override
public Set doScan(String... basePackages) {
Set beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
logger.warn("No MyBatis mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
} else {
processBeanDefinitions(beanDefinitions);
}
return beanDefinitions;
}
有的版本中MapperScannerRegistrar的registerBeanDefinitions方法并未直接通过ClassPathMapperScanner 扫描,而是将MapperScannerConfigurer注册到spring中,MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口,BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor,spring在启动时会调用MapperScannerConfigurer的postProcessBeanDefinitionRegistry方法,该方法会去扫描mapper,最终还是调用了MapperScannerRegistrar的processBeanDefinitions方法改变了mapper的bean定义。