溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Mybatis-spring自動注入機(jī)制原理

發(fā)布時間:2021-08-30 21:09:42 來源:億速云 閱讀:195 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要介紹“Mybatis-spring自動注入機(jī)制原理”,在日常操作中,相信很多人在Mybatis-spring自動注入機(jī)制原理問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Mybatis-spring自動注入機(jī)制原理”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

一、基礎(chǔ)背景

本篇文章的主要目的有兩個:

  • 項(xiàng)目中使用mybatis,我們只定義了mapper的接口,并沒有實(shí)現(xiàn),那這些實(shí)現(xiàn)類的bean是如何生成的?

  • mapper接口的實(shí)例bean是如何注入到spring容器的?

包名版本號
spring-boot2.1.9.RELEASE
mybatis-spring2.0.0
mybatis-plus-boot-starter3.1.0
mybatis3.5.0

二、源碼分析

項(xiàng)目中我們使用@MapperScan來配置mapper接口的路徑,如下圖

@EnableTransactionManagement
@Configuration
@MapperScan("com.ke.newhouse.agency.project.dao.mapper")
public class MybatisPlusConfiguration {
 
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

在這些mapper路徑下都是我們定義的接口,@MapperScan的作用有哪些呢,我們先看下@MapperScan的定義

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

在MapperScan的定義中我們目前只需要關(guān)注@Import(MapperScannerRegistrar.class),其含義是將MapperScannerRegistrar.class引入到spring容器中

public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
 
  private ResourceLoader resourceLoader;

  /**
   * {@inheritDoc}
   */
  @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);
 
    // this check is needed in Spring 3.1
    Optional.ofNullable(resourceLoader).ifPresent(scanner::setResourceLoader);
 
    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<>();
    basePackages.addAll(
        Arrays.stream(annoAttrs.getStringArray("value"))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList()));
 
    basePackages.addAll(
        Arrays.stream(annoAttrs.getStringArray("basePackages"))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList()));
 
    basePackages.addAll(
        Arrays.stream(annoAttrs.getClassArray("basePackageClasses"))
            .map(ClassUtils::getPackageName)
            .collect(Collectors.toList()));
 
    scanner.registerFilters();
    scanner.doScan(StringUtils.toStringArray(basePackages));
  }
}

可以看到MapperScannerRegistrar是繼承于ImportBeanDefinitionRegistrar接口,在spring中ImportBeanDefinitionRegistrar的也是創(chuàng)建bean的一種方式,它首先會定義好bean的一些基礎(chǔ)信息,如beanName, class等等,然后在spring啟動的時候調(diào)用其registerBeanDefinitions方法,來生成和注冊bean。

我們直接看scanner.doScan(StringUtils.toStringArray(basePackages));這行的工作,最終會調(diào)用下面的方法 ClassPathMapperScanner

private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
    GenericBeanDefinition definition;
    for (BeanDefinitionHolder holder : beanDefinitions) {
      definition = (GenericBeanDefinition) holder.getBeanDefinition();
      //這里的beanClassName是mapper接口的接口名(第一個字母小寫)
      String beanClassName = definition.getBeanClassName();
      LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName()
          + "' and '" + beanClassName + "' mapperInterface");
 
      // the mapper interface is the original class of the bean
      // but, the actual class of the bean is MapperFactoryBean
      definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
      //這行很重要,表示bean的實(shí)際class為MapperFactoryBean
      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) {
        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) {
        LOGGER.debug(() -> "Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
        //將該bean設(shè)置成按類型自動裝配,目的在該bean中如果有依賴其他bean,會按類型自動注入到該bean中
        definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
      }
    }
  }

我們再看MapperFactoryBean類

public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T> {

 private Class<T> mapperInterface;

 private boolean addToConfig = true;

 public MapperFactoryBean() {
   //intentionally empty
 }
  
 public MapperFactoryBean(Class<T> mapperInterface) {
   this.mapperInterface = mapperInterface;
 }

 /**
  * {@inheritDoc}
  */
 @Override
 protected void checkDaoConfig() {
   super.checkDaoConfig();

   notNull(this.mapperInterface, "Property 'mapperInterface' is required");
   //父類中的屬性SqlSessionTemplate,該字段是在上面講的自動裝配中注入的
   Configuration configuration = getSqlSession().getConfiguration();
   if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
     try {
       //將該mapper接口添加到MapperRegistry中去
       configuration.addMapper(this.mapperInterface);
     } catch (Exception e) {
       logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
       throw new IllegalArgumentException(e);
     } finally {
       ErrorContext.instance().reset();
     }
   }
 }

 /**
  * {@inheritDoc}
  */
 @Override
 public T getObject() throws Exception {
   return getSqlSession().getMapper(this.mapperInterface);
 }
·····
·····
}

MapperFactoryBean的父類是SqlSessionDaoSupport,同時實(shí)現(xiàn)了接口FactoryBean

我們先分析SqlSessionDaoSupport。

使得MapperFactoryBean擁有了SqlSessionTemplate屬性,而同時SqlSessionDaoSupport繼承于DaoSupport,DaoSupport是InitializingBean的一個抽象類并實(shí)現(xiàn)了afterPropertiesSet方法,該方法使得在bean生成時執(zhí)行一些操作checkDaoConfig。在checkDaoConfig方法中會將該mapper接口添加到MapperRegistry中去,MapperRegistry可以看作是一個mapper的注冊中心

MapperRegistry

public class MapperRegistry {
 
  private final Configuration config;
  //保存mapper接口與代理工廠類的映射
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
 
  public MapperRegistry(Configuration config) {
    this.config = config;
  }
 
  @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> boolean hasMapper(Class<T> type) {
    return knownMappers.containsKey(type);
  }
 
  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 {
        //將mapper接口與代理工廠類對應(yīng)起來
        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);
        }
      }
    }
  }
 
  /**
   * @since 3.2.2
   */
  public Collection<Class<?>> getMappers() {
    return Collections.unmodifiableCollection(knownMappers.keySet());
  }
 
  /**
   * @since 3.2.2
   */
  public void addMappers(String packageName, Class<?> superType) {
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
    for (Class<?> mapperClass : mapperSet) {
      addMapper(mapperClass);
    }
  }
 
  /**
   * @since 3.2.2
   */
  public void addMappers(String packageName) {
    addMappers(packageName, Object.class);
  }
 
}

MapperProxyFactory是MapperProxy的工廠類,MapperProxy是Mapper的代理類

MapperProxy

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)) {
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
    //使用緩存來保存MapperMethod
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    //最終會調(diào)用這里來執(zhí)行mapper中的方法
    return mapperMethod.execute(sqlSession, args);
  }
 
  private MapperMethod cachedMapperMethod(Method method) {
    return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
  }
 
  private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
      throws Throwable {
    final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
        .getDeclaredConstructor(Class.class, int.class);
    if (!constructor.isAccessible()) {
      constructor.setAccessible(true);
    }
    final Class<?> declaringClass = method.getDeclaringClass();
    return constructor
        .newInstance(declaringClass,
            MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
                | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
  }
 
 
}

我們在接著分析MapperFactoryBean的另一個功能接口FactoryBean,實(shí)現(xiàn)FactoryBean這個接口使得MapperFactoryBean成為了一個工廠bean,它的功能是:從spring容器中獲取該工廠bean的具體實(shí)例是通過getObject方法

MapperFactoryBean

public T getObject() throws Exception {
    return getSqlSession().getMapper(this.mapperInterface);
  }
 
 
····
 
public <T> T getMapper(Class<T> type) {
    return getConfiguration().getMapper(type, this);
  }
 
···
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
 
···
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 newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

可以看到最終從spring中獲取mapper的實(shí)例的時候,是獲取mapper的代理類

三、類UML圖

Mybatis-spring自動注入機(jī)制原理

四、結(jié)論

  • 使用mybaits,其中mapper接口最終的實(shí)例是MapperProxy生成的代理類

  • 通過ImportBeanDefinitionRegistrar這種方式來注入到spring容器中

到此,關(guān)于“Mybatis-spring自動注入機(jī)制原理”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI