1.mybatis springä»ç»ã使ç¨ãå®ç°åç
2.Mybatis-Spring原理分析 -- @MapperScan注解
3.org.mybatis.spring.mapper.mapperscannerconfigurerå¨åªä¸ªjarå
4.MyBatis 原理:扫描 Mapper 接口
mybatis springä»ç»ã使ç¨ãå®ç°åç
mavenä¾èµ<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency>使ç¨
SqlSessionFactoryBean å¯ä»¥å建sqlSessionFactoryï¼dataSourceæ¯èªå·±çæ°æ®æºçbean @MapperScan注解å¯ä»¥å¸®å©æ们æMyBatisçMapper类注å为beanï¼è¿æ ·æ们就å¯ä»¥å¨ä½¿ç¨çå°æ¹éè¿@Autowired/@Resourceå¼ç¨æ¥ä½¿ç¨ã
@MapperScan("com.github.liuzhengyang")@ConfigurationpublicclassMyBatisConfig{ @Autowired@BeanpublicSqlSessionFactoryBeansqlSessionFactoryBean(DataSourcedataSource){ SqlSessionFactoryBeansqlSessionFactoryBean=newSqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(dataSource);returnsqlSessionFactoryBean;}}å®ç°åçmybatis-spring帮å©æ们ç®åçå·¥ä½ã带æ¥çä»·å¼æ¯
SqlSessionFactoryå建çå·¥ä½ï¼ä½¿ç¨åççmybatiséè¦ç¨é ç½®æ件é ç½®mybatisï¼mybais-springå¯ä»¥ç¨@Bean代ç å建ã(è½ç¶mybatisä¹è½ç¨ä»£ç æ建ï¼ä¸è¿SqlSessionFactory被spring管çäºï¼å¨ä½¿ç¨çæ¶ååªéè¦@Autowireä¼æ´æ¹ä¾¿)
ä¸åéè¦æ¯æ¬¡openSessionãcloseï¼è¿äºå·¥ä½å¨mybatis-springå é¨å®ç°äºï¼mybatis-spring帮å©æ们å¤ææ¯å¦è¦openSession
Mapperç±»åæäºbeanï¼éè¦ä½¿ç¨çæ¶åç´æ¥@Autowiredå°±å¯ä»¥
æä¾çº¿ç¨å®å ¨çSqlSessionTemplate
SqlSessionFactoryå¦ä½å建SqlSessionFactoryéè¿SqlSessionFactoryBean#buildSqlSessionFactoryæ建ï¼è°ç¨æ¶æºæ¯SqlSessionFactoryBean.afterPropertiesSetã SqlSessionFactoryæ大éå¯é 置项ï¼è¿äºé 置项æç»è½¬å为SqlSessionFactoryçæ建åæ°(Configuration)
@OverridepublicvoidafterPropertiesSet()throwsException{ notNull(dataSource,"Property'dataSource'isrequired");notNull(sqlSessionFactoryBuilder,"Property'sqlSessionFactoryBuilder'isrequired");state((configuration==null&&configLocation==null)||!(configuration!=null&&configLocation!=null),"Property'configuration'and'configLocation'cannotspecifiedwithtogether");this.sqlSessionFactory=buildSqlSessionFactory();}protectedSqlSessionFactorybuildSqlSessionFactory()throwsException{ finalConfigurationtargetConfiguration;...XMLConfigBuilderxmlConfigBuilder=null;if(this.configuration!=null){ targetConfiguration=this.configuration;if(targetConfiguration.getVariables()==null){ targetConfiguration.setVariables(this.configurationProperties);}elseif(this.configurationProperties!=null){ targetConfiguration.getVariables().putAll(this.configurationProperties);}}elseif(this.configLocation!=null){ xmlConfigBuilder=newXMLConfigBuilder(this.configLocation.getInputStream(),null,this.configurationProperties);targetConfiguration=xmlConfigBuilder.getConfiguration();}else{ LOGGER.debug(()->"Property'configuration'or'configLocation'notspecified,usingdefaultMyBatisConfiguration");targetConfiguration=newConfiguration();Optional.ofNullable(this.configurationProperties).ifPresent(targetConfiguration::setVariables);}...returnthis.sqlSessionFactoryBuilder.build(targetConfiguration);}Mapperç±»å¦ä½æ³¨åæbeanå°BeanFactoryä¸ç使ç¨äºmybatis-springï¼ä¼æ«æç¹å®çMapperç±»ï¼@MapperScan注解æ§å¶ï¼æ§å¶æ 注äºä»»æ注解çæ¥å£å¯ä»¥è¢«æ³¨åä¸ï¼è¿å¯ä»¥é ç½®æ¥å£çparentå¤æï¼ï¼ç¶åä½ä¸ºBean注åå°beanFactoryä¸ï¼ä»èè½è¢«å ¶ä»çbeanä¾èµä½¿ç¨ã
@MapperpublicinterfaceUserMapper{ UsergetUserById(longid);}è¦å®ç°è¿æ ·çscanæºå¶ï¼å°±éè¦ä¸ä¸ªscan mapperçBeanPostProcessorï¼è¿ä¸ªprocessorä¸ï¼scanå½åclasspathä¸æ»¡è¶³MapperScané ç½®çpackageè¦æ±çç±»ï¼æ¥å£ï¼ï¼å¹¶ä¸å¤ææ¯å¦æ@Mapper注解ï¼å¦æ符åï¼å建BeanDefinition注åå°BeanFactoryä¸ãå¨getBeançæ¶åï¼è°ç¨MapperFactoryBean.getObjectæ¿å°çMapper代çï¼å®ç°æ¯Configuration.getMapper(Class type, SqlSession sqlSession), SqlSessionæ¯SqlSessionTemplateèªèº«ãæåå¨afterPropertiesSetï¼ä¼æ¿å°SqlSessionFactory.getConfiguration()ï¼è°ç¨addMapper(Class type)æ·»å å°mybatisä¸
为ä»ä¹å¢å äº@MapperScan注解ï¼å°±è½æ«æ注åMapperäºå¢ãä»MapperScanç±»å¯ä»¥çå°ï¼ä¸é¢æä¸ä¸ª@Import注解ï¼importäºMapperScannerRegistrar
@Import(MapperScannerRegistrar.class)@Repeatable(MapperScans.class)public@interfaceMapperScan{ ...}springç@Import注解ä¸è¬ç¨æ¥å¼ç¨å ¶ä»çConfigurationï¼è¿å¯ä»¥å¼ç¨ ImportSelectoråImportBeanDefinitionRegistrar å®ç°æå ¶ä»çComponentç±»ã
Provides functionality equivalent to the element in Spring XML. Allows for importing @Configuration classes, ImportSelector and ImportBeanDefinitionRegistrar implementations, as well as regular component classes (as of 4.2; analogous to AnnotationConfigApplicationContext.register).
æ»ä¹ï¼çä»·äºå£°æäºä¸ä¸ªMapperScannerRegistrar Beanãæ们çä¸ä¸MapperScannerRegistrarçå®ç°ï¼MapperScannerRegistratå®ç°äºImportBeanDefinitionRegistraråResourceLoaderAwareæ¥å£ã
ImportBeanDefinitionRegistraræ¥å£ï¼ç¨æ¥å¨å¤ç@Configurationç±»çæ¶åï¼å建bean definition级å«çbeanã
Interface to be implemented by types that register additional bean definitions when processing @Configuration classes. Useful when operating at the bean definition level (as opposed to @Bean method/instance level) is desired or necessary.
å¨springçrefreshé¶æ®µï¼æä¸æ¥æ¯invokeBeanFactoryPostProcessorsï¼ä¼è°ç¨å°ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistryï¼æç»ä¼è°ç¨å°loadBeanDefinitionsFromRegistrarsï¼è°ç¨å°MapperScannerRegistrar.registerBeanDefinitions
@OverridepublicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistryregistry){ intregistryId=System.identityHashCode(registry);if(this.registriesPostProcessed.contains(registryId)){ thrownewIllegalStateException("postProcessBeanDefinitionRegistryalreadycalledonthispost-processoragainst"+registry);}if(this.factoriesPostProcessed.contains(registryId)){ thrownewIllegalStateException("postProcessBeanFactoryalreadycalledonthispost-processoragainst"+registry);}this.registriesPostProcessed.add(registryId);processConfigBeanDefinitions(registry);}privatevoidloadBeanDefinitionsForConfigurationClass(ConfigurationClassconfigClass,TrackedConditionEvaluatortrackedConditionEvaluator){ if(trackedConditionEvaluator.shouldSkip(configClass)){ StringbeanName=configClass.getBeanName();if(StringUtils.hasLength(beanName)&&this.registry.containsBeanDefinition(beanName)){ this.registry.removeBeanDefinition(beanName);}this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());return;}if(configClass.isImported()){ registerBeanDefinitionForImportedConfigurationClass(configClass);}for(BeanMethodbeanMethod:configClass.getBeanMethods()){ loadBeanDefinitionsForBeanMethod(beanMethod);}loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());}privatevoidloadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar,AnnotationMetadata>registrars){ registrars.forEach((registrar,metadata)->registrar.registerBeanDefinitions(metadata,this.registry));}åçä¸ä¸MapperScannerRegistrarçå®ç°ãregisterBeanDefinitionså建äºä¸ä¸ªBeanDefinitionï¼beanæ¯MapperScannerConfigurerï¼é ç½®äºMapperScannerConfigureréè¦çå±æ§é ç½®ï¼é ç½®æ¥æºäº@MapperScan注解)ï¼ä¾å¦annotationClass, factoryBeançã
publicclassMapperScannerRegistrarimplementsImportBeanDefinitionRegistrar,ResourceLoaderAware{ @OverridepublicvoidregisterBeanDefinitions(AnnotationMetadataimportingClassMetadata,BeanDefinitionRegistryregistry){ AnnotationAttributesmapperScanAttrs=AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));if(mapperScanAttrs!=null){ registerBeanDefinitions(importingClassMetadata,mapperScanAttrs,registry,generateBaseBeanName(importingClassMetadata,0));}}voidregisterBeanDefinitions(AnnotationMetadataannoMeta,AnnotationAttributesannoAttrs,BeanDefinitionRegistryregistry,StringbeanName){ BeanDefinitionBuilderbuilder=BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);builder.addPropertyValue("processPropertyPlaceHolders",true);Class<?extendsAnnotation>annotationClass=annoAttrs.getClass("annotationClass");if(!Annotation.class.equals(annotationClass)){ builder.addPropertyValue("annotationClass",annotationClass);}Class<?>markerInterface=annoAttrs.getClass("markerInterface");if(!Class.class.equals(markerInterface)){ builder.addPropertyValue("markerInterface",markerInterface);}Class<?extendsBeanNameGenerator>generatorClass=annoAttrs.getClass("nameGenerator");if(!BeanNameGenerator.class.equals(generatorClass)){ builder.addPropertyValue("nameGenerator",BeanUtils.instantiateClass(generatorClass));}Class<?extendsMapperFactoryBean>mapperFactoryBeanClass=annoAttrs.getClass("factoryBean");if(!MapperFactoryBean.class.equals(mapperFactoryBeanClass)){ builder.addPropertyValue("mapperFactoryBeanClass",mapperFactoryBeanClass);}StringsqlSessionTemplateRef=annoAttrs.getString("sqlSessionTemplateRef");if(StringUtils.hasText(sqlSessionTemplateRef)){ builder.addPropertyValue("sqlSessionTemplateBeanName",annoAttrs.getString("sqlSessionTemplateRef"));}StringsqlSessionFactoryRef=annoAttrs.getString("sqlSessionFactoryRef");if(StringUtils.hasText(sqlSessionFactoryRef)){ builder.addPropertyValue("sqlSessionFactoryBeanName",annoAttrs.getString("sqlSessionFactoryRef"));}List<String>basePackages=newArrayList<>();basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("value")).filter(StringUtils::hasText).collect(Collectors.toList()));basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("basePackages")).filter(StringUtils::hasText).collect(Collectors.toList()));basePackages.addAll(Arrays.stream(annoAttrs.getClassArray("basePackageClasses")).map(ClassUtils::getPackageName).collect(Collectors.toList()));if(basePackages.isEmpty()){ basePackages.add(getDefaultBasePackage(annoMeta));}StringlazyInitialization=annoAttrs.getString("lazyInitialization");if(StringUtils.hasText(lazyInitialization)){ builder.addPropertyValue("lazyInitialization",lazyInitialization);}StringdefaultScope=annoAttrs.getString("defaultScope");if(!AbstractBeanDefinition.SCOPE_DEFAULT.equals(defaultScope)){ builder.addPropertyValue("defaultScope",defaultScope);}builder.addPropertyValue("basePackage",StringUtils.collectionToCommaDelimitedString(basePackages));registry.registerBeanDefinition(beanName,builder.getBeanDefinition());}privatestaticStringgenerateBaseBeanName(AnnotationMetadataimportingClassMetadata,intindex){ returnimportingClassMetadata.getClassName()+"#"+MapperScannerRegistrar.class.gMybatis-Spring原理分析 -- @MapperScan注解
根据@MapperScan注解配置的包路径,扫描所有mapper接口,创建BeanDefinition对象,修改beanClass属性值为MapperFactoryBean,注册到Spring容器中,为后续Bean初始化做准备。suntv源码
在启动流程中,Spring扩展点ImportBeanDefinitionRegistrar被触发,其注册BeanDefinition到容器。同时,BeanDefinitionRegistryPostProcessor也被激活,创建ClassPathMapperScanner对象,对@MapperScacn中的包路径进行扫描,创建并修改BeanDefinition。
ImportBeanDefinitionRegistrar是投票微信源码Spring扩展点之一,其在启动时回调registerBeanDefinitions方法,将MapperScannerConfigurer的BeanDefinition注册到容器中。
而BeanDefinitionRegistryPostProcessor也是Spring的扩展点之一,在启动时回调postProcessBeanDefinitionRegistry方法,创建ClassPathMapperScanner对象,对@MapperScacn定义的包路径进行扫描,创建、主力开盘指标源码修改BeanDefinition。
ClassPathMapperScanner负责扫描mapper层的所有接口,创建Bean定义,并设置beanClass和autoWireMode。
最后,创建MapperFactoryBean,其属性根据扫描到的音派app 源码mapper接口自动配置,完成初始化。
org.mybatis.spring.mapper.mapperscannerconfigurerå¨åªä¸ªjarå
org.mybatis.spring.mapper.MapperScannerConfigurer æ¥èª mybatis-spring
å¦æä½ ä½¿ç¨ mavençè¯, ä½ å¯ä»¥è¿ä¹é ç½®
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
MyBatis 原理:扫描 Mapper 接口
在MyBatis中,Mapper接口的扫描依赖MyBatis和Spring项目。实现Mapper接口的自动扫描主要有两种方式:@Mapper和@MapperScan注解。
@Mapper注解通常用于Mapper接口上,若仅需扫描带有该注解的接口,需引入mybatis/spring-boot-starter项目。源码怎么变成用户在Spring未找到MapperScannerConfigurer和MapperFactoryBean的Bean时,AutoConfiguredMapperScannerRegistrar会自动扫描并注入Mapper接口的实现类。这个过程可通过MybatisAutoConfiguration的源码来理解。
相比之下,@MapperScan注解是Mybatis的常见扫描方式。它通过@Import(MapperScannerRegistrar.class)导入MapperScannerRegistrar,进行Mapper扫描逻辑。MapperScannerRegistrar通过实现ImportBeanDefinitionRegistrar接口的registerBeanDefinitions方法完成Mapper的扫描。
核心组件MapperScannerConfigurer实现了BeanDefinitionRegistryPostProcessor接口,其主要在registerBeanDefinitions方法中处理Mapper的自动注入。具体来说,它会创建ClassPathMapperScanner,扫描指定包中的Mapper,生成BeanDefinition,这些BeanDefinition最终会在Spring的Bean创建过程中被转换为Mapper的实例。
MapperFactoryBean是MyBatis/Spring用来表示Mapper的Bean,它基于SqlSessionDaoSupport,提供了FactoryBean接口的实现。获取Mapper时,会通过FactoryBean的getObject方法返回Mapper的代理类,如SqlSessionTemplate,它与Spring事务紧密关联并支持线程安全。
Configuration和MapperRegistry是MyBatis的核心配置,前者管理Mapper的信息,后者存储Mapper实例。在使用MapperRegistry获取Mapper时,会优先尝试从缓存中获取,只有当缓存中不存在时,才会创建新的MapperProxy实例。