欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Spring中實現(xiàn)接口動態(tài)的解決方法

 更新時間:2017年07月27日 09:28:03   作者:跡_Jason  
最近在工作遇到的一個,發(fā)現(xiàn)網(wǎng)上的資料較少,所以想著總結(jié)分享下,下面這篇文章主要給大家介紹了關(guān)于Spring中實現(xiàn)接口動態(tài)的解決方法,文中通過完整的示例代碼給大家介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文主要給大家介紹的是關(guān)于Spring實現(xiàn)接口動態(tài)的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說,來一起看看詳細(xì)的介紹吧。

關(guān)于這個問題是因為領(lǐng)導(dǎo)最近跟我提了一個需求,是有關(guān)于實現(xiàn)類Mybatis的@Select、@Insert注解的功能。其是基于interface層面,不存在任何的接口實現(xiàn)類。因而在實現(xiàn)的過程中,首先要解決的是如何動態(tài)實現(xiàn)接口的實例化。其次是如何將使接口根據(jù)注解實現(xiàn)相應(yīng)的功能。

聲明

解決方案是基于Mybatis源碼,進(jìn)行二次開發(fā)實現(xiàn)。

解決方法

我們先來看看Mybatis是如何實現(xiàn)Dao類的掃描的。

MapperScannerConfigurer.java

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
 if (this.processPropertyPlaceHolders) {
  processPropertyPlaceHolders();
 }

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

ClassPathMapperScanner是Mybatis繼承ClassPathBeanDefinitionScanner類而來的。這里對于ClassPathMapperScanner的配置參數(shù)來源于我們在使用Mybatis時的配置而來,是不是還記得在使用Mybatis的時候要配置basePackage的參數(shù)呢?

接著我們就順著scanner.scan()方法,進(jìn)入查看一下里面的實現(xiàn)。

ClassPathBeanDefinitionScanner.java

public int scan(String... basePackages) {
 int beanCountAtScanStart = this.registry.getBeanDefinitionCount();

 doScan(basePackages);

 // Register annotation config processors, if necessary.
 if (this.includeAnnotationConfig) {
  AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
 }

 return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}

這里關(guān)鍵的代碼是doScan(basePackages); ,那么我們在進(jìn)去看一下??赡苣銜吹降氖荢pring源碼的實現(xiàn)方法,但這里Mybatis也實現(xiàn)了自己的一套,我們看一下Mybatis的實現(xiàn)。

ClassPathMapperScanner.java

public Set<BeanDefinitionHolder> doScan(String... basePackages) {
 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 {
 for (BeanDefinitionHolder holder : beanDefinitions) {
  GenericBeanDefinition 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.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
  definition.setBeanClass(MapperFactoryBean.class);

  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) {
  if (logger.isDebugEnabled()) {
   logger.debug("Enabling autowire by type for MapperFactoryBean with name '" + holder.getBeanName() + "'.");
  }
  definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
  }
 }
 }

 return beanDefinitions;
}

definition.setBeanClass(MapperFactoryBean.class);這行代碼是非常關(guān)鍵的一句,由于在Spring中存在兩種自動實例化的方式,一種是我們常用的本身的接口實例化類進(jìn)行接口實例化,還有一種就是這里的自定義實例化。而這里的setBeanClass方法就是在BeanDefinitionHolder中進(jìn)行配置。在Spring進(jìn)行實例化的時候進(jìn)行處理。

那么我們在看一下MapperFactoryBean.class

MapperFactoryBean.java

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

 private Class<T> mapperInterface;

 private boolean addToConfig = true;

 /**
 * Sets the mapper interface of the MyBatis mapper
 *
 * @param mapperInterface class of the interface
 */
 public void setMapperInterface(Class<T> mapperInterface) {
 this.mapperInterface = mapperInterface;
 }

 /**
 * If addToConfig is false the mapper will not be added to MyBatis. This means
 * it must have been included in mybatis-config.xml.
 * <p>
 * If it is true, the mapper will be added to MyBatis in the case it is not already
 * registered.
 * <p>
 * By default addToCofig is true.
 *
 * @param addToConfig
 */
 public void setAddToConfig(boolean addToConfig) {
 this.addToConfig = addToConfig;
 }

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

 notNull(this.mapperInterface, "Property 'mapperInterface' is required");

 Configuration configuration = getSqlSession().getConfiguration();
 if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
  try {
  configuration.addMapper(this.mapperInterface);
  } catch (Throwable t) {
  logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", t);
  throw new IllegalArgumentException(t);
  } finally {
  ErrorContext.instance().reset();
  }
 }
 }

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

 /**
 * {@inheritDoc}
 */
 public Class<T> getObjectType() {
 return this.mapperInterface;
 }

 /**
 * {@inheritDoc}
 */
 public boolean isSingleton() {
 return true;
 }

在該類中其實現(xiàn)了FactoryBean接口,看過Spring源碼的人,我相信對其都有很深的印象,其在Bean的實例化中起著很重要的作用。在該類中我們要關(guān)注的是getObject方法,我們之后將動態(tài)實例化的接口對象放到Spring實例化列表中,這里就是入口,也是我們的起點。不過要特別說明的是mapperInterface的值是如何被賦值的,可能會有疑問,我們再來看看上面的ClassPathMapperScanner.java我們在配置MapperFactoryBean.class的上面存在一行 definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());其在之后在Spring的PostProcessorRegistrationDelegate類的populateBean方法中進(jìn)行屬性配置,會將其依靠反射的方式將其注入到MapperFactoryBean.class中。

而且definition.getPropertyValues().add中添加的值是注入到MapperFactoryBean對象中去的。這一點需要說明一下。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

  • java外賣訂餐系統(tǒng)小項目

    java外賣訂餐系統(tǒng)小項目

    這篇文章主要為大家詳細(xì)介紹了java外賣訂餐系統(tǒng)小項目,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-01-01
  • java打包maven啟動報錯jar中沒有主清單屬性

    java打包maven啟動報錯jar中沒有主清單屬性

    本文主要介紹了java打包maven啟動報錯jar中沒有主清單屬性,可能原因是創(chuàng)建springboot項目時,自動導(dǎo)入,下面就來介紹一下解決方法,感興趣的可以了解一下
    2024-03-03
  • java pdf加水印的方法

    java pdf加水印的方法

    這篇文章主要為大家詳細(xì)介紹了java pdf加水印的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-08-08
  • Java并發(fā)容器ConcurrentLinkedQueue解析

    Java并發(fā)容器ConcurrentLinkedQueue解析

    這篇文章主要介紹了Java并發(fā)容器ConcurrentLinkedQueue解析,
    2023-12-12
  • Java?如何通過注解實現(xiàn)接口輸出時數(shù)據(jù)脫敏

    Java?如何通過注解實現(xiàn)接口輸出時數(shù)據(jù)脫敏

    這篇文章主要介紹了Java?如何通過注解實現(xiàn)接口輸出時數(shù)據(jù)脫敏,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • spring @profile注解的使用方法

    spring @profile注解的使用方法

    本篇文章主要介紹了spring @profile注解的使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Redisson之分布式鎖原理全面分析

    Redisson之分布式鎖原理全面分析

    這篇文章主要介紹了Redisson分布式鎖原理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • SpringBoot之自定義Banner詳解

    SpringBoot之自定義Banner詳解

    這篇文章主要介紹了SpringBoot之自定義Banner詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • Java實現(xiàn)記事本功能

    Java實現(xiàn)記事本功能

    這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)記事本功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Java設(shè)計模式中橋接模式應(yīng)用詳解

    Java設(shè)計模式中橋接模式應(yīng)用詳解

    橋接,顧名思義,就是用來連接兩個部分,使得兩個部分可以互相通訊。橋接模式將系統(tǒng)的抽象部分與實現(xiàn)部分分離解耦,使他們可以獨立的變化。本文通過示例詳細(xì)介紹了橋接模式的原理與使用,需要的可以參考一下
    2022-11-11

最新評論