Mybatis是如何集成到Spring容器中的

在現在的JavaEE開發過程中,我們經常會使用到Spring+SpringMVC+Mybatis這個組合。那麼Mybatis是如何集成到Spring中的呢?

本文只講@MapperScan註解方式的整個過程。其他方式類似。

Mapper集成到Spring使用大概分爲如下幾個步驟:

  1. 使用Import方式引入註冊類MapperScannerRegistrar
  2. MapperScannerRegistrar獲取配置參數。
  3. 使用ClassPathMapperScanner進行掃描。比如掃描basePackages下面的類。然後對掃描的bean定義處理,比如替換beanClass爲MapperFactoryBean.class
  4. Sping進行註冊bean,調用到MapperFactoryBean的getObject()。返回一個代理對象MapperProxy
  5. 使用代理對象進行增刪改查,接口方法會被代理到MapperMethod,最終用sqlSession進行增刪改查。

一、使用Import方式引入註冊類MapperScannerRegistrar

先看@MapperScan代碼

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

這個註解中有一個@Import(MapperScannerRegistrar.class)。
這個@Import在Spring解析中會先去實例化一個MapperScannerRegistrar.class的單例bean到Spring中。

二、MapperScannerRegistrar

MapperScannerRegistrar實現了ImportBeanDefinitionRegistrar接口。ImportBeanDefinitionRegistrar會返回@Import中定義參數,然後我們使用
ClassPathMapperScanner掃描。

@Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

    AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
    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));
  }

三、 使用ClassPathMapperScanner進行掃描

ClassPathMapperScanner繼承了ClassPathBeanDefinitionScanner,可以掃描我們需要的bean定義。比如我們經常配置的basePackages。他就會給我掃描下面所有的類,然後對掃描的Mapper bean定義進行處理。後面Spring對掃描的beanDefintion進行初始化等操作。

下面是ClassPathMapperScanner中處理bean定義的方法

 private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    //遍歷bean定義
    for (BeanDefinitionHolder holder : beanDefinitions) {
       //BeanDefinitionHolder會包裝一個BeanDefinition
      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
	
	//此處把bean定義的構造方法中加一個參數
	//其實後面調用的MapperFactoryBean的這個構造方法,這個構造方法需要一個class。這個class就是掃描出來的Mapper的class
	//public MapperFactoryBean(Class<T> mapperInterface) {
	 //   this.mapperInterface = mapperInterface;
	 // }      
 definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName()); // issue #59

// 此處會把   beanClass替換爲MapperFactoryBean.class,後續spring進行初始化的時候就會通過MapperFactoryBean.class進行反射
  definition.setBeanClass(this.mapperFactoryBean.getClass());
//添加參數
      definition.getPropertyValues().add("addToConfig", this.addToConfig);
//下面的if沒有設置一般都不會進入
      boolean explicitFactoryUsed = false;
      if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
        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() + "'.");
        }
    //設置@autowire的方式爲class
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
      }
    }
  }

四、 Sping進行註冊MapperFactoryBean

在Spring中有一個比較特殊的bean較FactoryBean。這個bean爲使用者提供了一種靈活初始化bean的方式,Spring在構造FactoryBean類型的bean的時候會調用FactoryBean.getObject()進行初始化bean。
下面是MapperFactoryBean初始化bean的方法

  @Override
  public T getObject() throws Exception {
  //會返回一個MapperProxy的類,Spring就會把MapperProxy註冊到容器中,當使用Mapper的類型獲取bean的時候其實spring返回的是一個MapperProxy代理對象。
    return getSqlSession().getMapper(this.mapperInterface);
  }

返回MapperProxy的方法是通過MapperRegistry.getMapper返回的

  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);
    }
  }

進入MapperProxyFactory類

public class MapperProxyFactory<T> {
//mapper接口的class
  private final Class<T> mapperInterface;
  //MapperMethod緩存
  private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
  
  public MapperProxyFactory(Class<T> mapperInterface) {
    this.mapperInterface = mapperInterface;
  }

  public Class<T> getMapperInterface() {
    return mapperInterface;
  }

  public Map<Method, MapperMethod> getMethodCache() {
    return methodCache;
  }

  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
  //使用JDK動態代理爲mapperInterface創建一個mapperProxy的動態代理,後續調用mapperInterface方法的時候會進入mapperProxy的invoke方法。invoke會代理mapperInterface的方法調用。
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
  //new一個MapperProxy代理對象
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

}

五. 使用代理對象進行增刪改查

MapperProxy其實就是一個InvocationHandler,MapperProxy代理所有的Mapper方法調用。

public class MapperProxy<T> implements InvocationHandler, Serializable {

  private static final long serialVersionUID = -6424540398559729838L;
  private final SqlSession sqlSession;
  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethod> methodCache;

  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
    this.methodCache = methodCache;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
    //代理的對象是否爲實體類
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {//是否爲接口的default方法
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //接口Mapper一般都是進入這裏,這邊會用一個MapperMethod進行調用,裏面其實就是一個sqlSeesion的調用。
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

到這裏mybatis中Mapper如何集成到Spring的大概就完了。
那麼sqlSession如何集成到Spring的呢?

其實很簡單,sqlSession其實需要我們自己手動配置,mybatis-spring中爲我們提供了一個SqlSessionFactoryBean,這個也是一個FactoryBean。SqlSessionFactoryBean會返回一個SqlSessionFactory。SqlSessionFactory註冊到Spring中。在使用sqlSession的地方直接通過SqlSessionFactory返回即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章