詳解Spring中實現(xiàn)接口動態(tài)的解決方法
前言
本文主要給大家介紹的是關(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并發(fā)容器ConcurrentLinkedQueue解析
這篇文章主要介紹了Java并發(fā)容器ConcurrentLinkedQueue解析,2023-12-12Java?如何通過注解實現(xiàn)接口輸出時數(shù)據(jù)脫敏
這篇文章主要介紹了Java?如何通過注解實現(xiàn)接口輸出時數(shù)據(jù)脫敏,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12