您好,登錄后才能下訂單哦!
前言
本文主要給大家介紹的是關于Spring實現接口動態的相關內容,分享出來供大家參考學習,下面話不多說,來一起看看詳細的介紹吧。
關于這個問題是因為領導最近跟我提了一個需求,是有關于實現類Mybatis的@Select、@Insert注解的功能。其是基于interface層面,不存在任何的接口實現類。因而在實現的過程中,首先要解決的是如何動態實現接口的實例化。其次是如何將使接口根據注解實現相應的功能。
聲明
解決方案是基于Mybatis源碼,進行二次開發實現。
解決方法
我們先來看看Mybatis是如何實現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的配置參數來源于我們在使用Mybatis時的配置而來,是不是還記得在使用Mybatis的時候要配置basePackage的參數呢?
接著我們就順著scanner.scan()
方法,進入查看一下里面的實現。
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); }
這里關鍵的代碼是doScan(basePackages);
,那么我們在進去看一下。可能你會看到的是Spring源碼的實現方法,但這里Mybatis也實現了自己的一套,我們看一下Mybatis的實現。
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);
這行代碼是非常關鍵的一句,由于在Spring中存在兩種自動實例化的方式,一種是我們常用的本身的接口實例化類進行接口實例化,還有一種就是這里的自定義實例化。而這里的setBeanClass方法就是在BeanDefinitionHolder中進行配置。在Spring進行實例化的時候進行處理。
那么我們在看一下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; }
在該類中其實現了FactoryBean接口,看過Spring源碼的人,我相信對其都有很深的印象,其在Bean的實例化中起著很重要的作用。在該類中我們要關注的是getObject方法,我們之后將動態實例化的接口對象放到Spring實例化列表中,這里就是入口,也是我們的起點。不過要特別說明的是mapperInterface的值是如何被賦值的,可能會有疑問,我們再來看看上面的ClassPathMapperScanner.java我們在配置MapperFactoryBean.class的上面存在一行 definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
其在之后在Spring的PostProcessorRegistrationDelegate類的populateBean方法中進行屬性配置,會將其依靠反射的方式將其注入到MapperFactoryBean.class中。
而且definition.getPropertyValues().add
中添加的值是注入到MapperFactoryBean對象中去的。這一點需要說明一下。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。