詳解Spring中實(shí)現(xiàn)接口動(dòng)態(tài)的解決方法
前言
本文主要給大家介紹的是關(guān)于Spring實(shí)現(xiàn)接口動(dòng)態(tài)的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面話不多說,來一起看看詳細(xì)的介紹吧。
關(guān)于這個(gè)問題是因?yàn)轭I(lǐng)導(dǎo)最近跟我提了一個(gè)需求,是有關(guān)于實(shí)現(xiàn)類Mybatis的@Select、@Insert注解的功能。其是基于interface層面,不存在任何的接口實(shí)現(xiàn)類。因而在實(shí)現(xiàn)的過程中,首先要解決的是如何動(dòng)態(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類而來的。這里對(duì)于ClassPathMapperScanner的配置參數(shù)來源于我們?cè)谑褂肕ybatis時(shí)的配置而來,是不是還記得在使用Mybatis的時(shí)候要配置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);
,那么我們?cè)谶M(jìn)去看一下??赡苣銜?huì)看到的是Spring源碼的實(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中存在兩種自動(dòng)實(shí)例化的方式,一種是我們常用的本身的接口實(shí)例化類進(jìn)行接口實(shí)例化,還有一種就是這里的自定義實(shí)例化。而這里的setBeanClass方法就是在BeanDefinitionHolder中進(jìn)行配置。在Spring進(jìn)行實(shí)例化的時(shí)候進(jìn)行處理。
那么我們?cè)诳匆幌翸apperFactoryBean.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源碼的人,我相信對(duì)其都有很深的印象,其在Bean的實(shí)例化中起著很重要的作用。在該類中我們要關(guān)注的是getObject方法,我們之后將動(dòng)態(tài)實(shí)例化的接口對(duì)象放到Spring實(shí)例化列表中,這里就是入口,也是我們的起點(diǎn)。不過要特別說明的是mapperInterface的值是如何被賦值的,可能會(huì)有疑問,我們?cè)賮砜纯瓷厦娴腃lassPathMapperScanner.java我們?cè)谂渲肕apperFactoryBean.class的上面存在一行 definition.getPropertyValues().add("mapperInterface", definition.getBeanClassName());
其在之后在Spring的PostProcessorRegistrationDelegate類的populateBean方法中進(jìn)行屬性配置,會(huì)將其依靠反射的方式將其注入到MapperFactoryBean.class中。
而且definition.getPropertyValues().add
中添加的值是注入到MapperFactoryBean對(duì)象中去的。這一點(diǎn)需要說明一下。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
java打包maven啟動(dòng)報(bào)錯(cuò)jar中沒有主清單屬性
本文主要介紹了java打包maven啟動(dòng)報(bào)錯(cuò)jar中沒有主清單屬性,可能原因是創(chuàng)建springboot項(xiàng)目時(shí),自動(dòng)導(dǎo)入,下面就來介紹一下解決方法,感興趣的可以了解一下2024-03-03Java并發(fā)容器ConcurrentLinkedQueue解析
這篇文章主要介紹了Java并發(fā)容器ConcurrentLinkedQueue解析,2023-12-12Java?如何通過注解實(shí)現(xiàn)接口輸出時(shí)數(shù)據(jù)脫敏
這篇文章主要介紹了Java?如何通過注解實(shí)現(xiàn)接口輸出時(shí)數(shù)據(jù)脫敏,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java設(shè)計(jì)模式中橋接模式應(yīng)用詳解
橋接,顧名思義,就是用來連接兩個(gè)部分,使得兩個(gè)部分可以互相通訊。橋接模式將系統(tǒng)的抽象部分與實(shí)現(xiàn)部分分離解耦,使他們可以獨(dú)立的變化。本文通過示例詳細(xì)介紹了橋接模式的原理與使用,需要的可以參考一下2022-11-11