溫馨提示×

溫馨提示×

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

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

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

發(fā)布時間:2020-09-24 19:11:32 來源:腳本之家 閱讀:182 作者:跡_Jason 欄目:編程語言

前言

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

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

聲明

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

解決方法

我們先來看看Mybatis是如何實(shí)現(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)入查看一下里面的實(shí)現(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源碼的實(shí)現(xiàn)方法,但這里Mybatis也實(shí)現(xiàn)了自己的一套,我們看一下Mybatis的實(shí)現(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中存在兩種自動實(shí)例化的方式,一種是我們常用的本身的接口實(shí)例化類進(jìn)行接口實(shí)例化,還有一種就是這里的自定義實(shí)例化。而這里的setBeanClass方法就是在BeanDefinitionHolder中進(jìn)行配置。在Spring進(jìn)行實(shí)例化的時候進(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;
 }

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

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

總結(jié)

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

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

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

AI