Spring源码系列(九)MapperScan注解的原理(一)

作者:神秘网友 发布时间:2020-10-15 17:24:57

Spring源码系列(九)MapperScan注解的原理(一)

Spring源码系列(九)MapperScan注解的原理(一)

前面的博客已经写了BeanFactoryPostProcessor的执行的时机和顺序,同时也介绍了对应的扫描机制,笔者也通过模拟了一个自定义的注解来模拟MapperScan注解,但是由于篇幅的原因,笔者只简单的模拟了一下,今天笔者决定花一篇博客来介绍一下MapperScan的源码,同时由于MapperScan有两个版本,笔者也会一一介绍。

由于本篇博客博客是讲源码的,所以这儿的应用不会深入的讲,只会讲一些简单的使用,我们先打开mybatis的官网,可以看到mybatis总共有两个版本

Spring源码系列(九)MapperScan注解的原理(一)

可以看到官网主要是两个版本,有两个版本,是因为这两个版本的实现的方式是不同,今天笔者会对这两种的版本的源码的进行讲解。

spring怎么整合mybatis源码,也可以参考这个官网。但是笔者不喜欢使用xml的配置,于是笔者使用全注解的方式,我们先看下笔者操作的数据库,具体的如下:

Spring源码系列(九)MapperScan注解的原理(一)

我们直接上代码,看怎么使用的,具体的代码如下:

package com.ys.mybatisMapperScan.entity;

public class Test {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Test{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

package com.ys.mybatisMapperScan.mapper;

import com.ys.mybatisMapperScan.entity.Test;
import org.apache.ibatis.annotations.Select;

public interface TestMapper {

    @Select("select * from t_test where id = #{id}")
    Test selectById(int id);
}

package com.ys.mybatisMapperScan;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.ys.mybatisMapperScan.mapper")
public class AppConfig {

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(Driver.class.getName());
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sessionFactoryBean(@Autowired DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        return sqlSessionFactory;
    }
}

package com.ys.mybatisMapperScan;

import com.ys.mybatisMapperScan.mapper.TestMapper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        System.out.println(applicationContext.getBean(TestMapper.class));
        System.out.println(applicationContext.getBean(TestMapper.class).selectById(1));
    }
}

具体的运行的结果如下:

Spring源码系列(九)MapperScan注解的原理(一)

可以看到打印的TestMapper是一个代理对象,然后查询的结果也出来了。可以看到spring整合mybatis就完成。

这个是在解析配置类的时候调用的,具体的调用链如下:

AbstractApplicationContext#refresh
--->AbstractApplicationContext#invokeBeanFactoryPostProcessors
--->PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory, List<BeanFactoryPostProcessor>)
--->PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors
--->ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry
--->ConfigurationClassPostProcessor#processConfigBeanDefinitions

这个调用链中的方法笔者在前面的博客基本已经介绍,只有processConfigBeanDefinitions方法没有介绍完,具体的代码如下:

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    //创建一个集合用来存BeanDefinitionHolder
    List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    //获取所有的BeanDefinition的name
	String[] candidateNames = registry.getBeanDefinitionNames();

    //遍历所有的BeanDefinition的name找出其中的配置类
	for (String beanName : candidateNames) {
        //根BeanDefinition的name获取对应的BeanDefinition
		BeanDefinition beanDef = registry.getBeanDefinition(beanName);
        //如果对应的这个属性的值不为空的话则表示已经解析过了。
		if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
			}
		}
        //如果这个值为空,则判断这个BeanDefinition是不是配置值
        //什么样的类会被解析成配置类?
        //如果加了Configuration注解的值就会被解析成full的配置类
        //不是接口,加了Component ComponentScan Import ImportResource 四个注解中一个再或者是有方法添加了Bean注解会被解析成lite的配置类
        //具体的详情之前的博客已经讲了
		else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
			configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
		}
	}

	// Return immediately if no @Configuration classes were found
    // 判断是否找到了对应的配置类
	if (configCandidates.isEmpty()) {
		return;
	}

	// Sort by previously determined @Order value, if applicable
    // 对找到的配置类进行对应的排序,排序的配置就是看加了@Order注解中的值
	configCandidates.sort((bd1, bd2) -> {
		int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
		int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
		return Integer.compare(i1, i2);
	});

	// Detect any custom bean name generation strategy supplied through the enclosing application context
    // 获取对应的名字生成策略
	SingletonBeanRegistry sbr = null;
	if (registry instanceof SingletonBeanRegistry) {
		sbr = (SingletonBeanRegistry) registry;
		if (!this.localBeanNameGeneratorSet) {
			BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
					AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
			if (generator != null) {
				this.componentScanBeanNameGenerator = generator;
				this.importBeanNameGenerator = generator;
			}
		}
	}

	if (this.environment == null) {
		this.environment = new StandardEnvironment();
	}

	// Parse each @Configuration class
    // 创建对应的解析对象
	ConfigurationClassParser parser = new ConfigurationClassParser(
			this.metadataReaderFactory, this.problemReporter, this.environment,
			this.resourceLoader, this.componentScanBeanNameGenerator, registry);

    //待解析的配置类
	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    //已经解析的配置类
	Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
	do {
        //解析对应的配置类
		parser.parse(candidates);
		parser.validate();

		Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
		configClasses.removeAll(alreadyParsed);

		// Read the model and create bean definitions based on its content
		if (this.reader == null) {
			this.reader = new ConfigurationClassBeanDefinitionReader(
					registry, this.sourceExtractor, this.resourceLoader, this.environment,
					this.importBeanNameGenerator, parser.getImportRegistry());
		}
		this.reader.loadBeanDefinitions(configClasses);
		alreadyParsed.addAll(configClasses);

		candidates.clear();
		if (registry.getBeanDefinitionCount() > candidateNames.length) {
			String[] newCandidateNames = registry.getBeanDefinitionNames();
			Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
			Set<String> alreadyParsedClasses = new HashSet<>();
			for (ConfigurationClass configurationClass : alreadyParsed) {
				alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
			}
			for (String candidateName : newCandidateNames) {
				if (!oldCandidateNames.contains(candidateName)) {
					BeanDefinition bd = registry.getBeanDefinition(candidateName);
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
							!alreadyParsedClasses.contains(bd.getBeanClassName())) {
						candidates.add(new BeanDefinitionHolder(bd, candidateName));
					}
				}
			}
			candidateNames = newCandidateNames;
		}
	}
	while (!candidates.isEmpty());

	// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
	if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
		sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
	}

	if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
		// Clear cache in externally provided MetadataReaderFactory; this is a no-op
		// for a shared cache since it'll be cleared by the ApplicationContext.
		((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
	}
}

上次解析配置类的代码,只讲解析@MapperScan注解的解析,今天我们要讲的是解析@Import注解的源码,首先我们先看parser.parse(candidates);,具体的代码如下:

public void parse(Set<BeanDefinitionHolder> configCandidates) {
    //遍历所有的配置类,进行解析
	for (BeanDefinitionHolder holder : configCandidates) {
		BeanDefinition bd = holder.getBeanDefinition();
		try {
            //加了注解的配置类不用说肯定进入下面这个解析的方法。
			if (bd instanceof AnnotatedBeanDefinition) {
				parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
			}
			else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
				parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
			}
			else {
				parse(bd.getBeanClassName(), holder.getBeanName());
			}
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanDefinitionStoreException(
					"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
		}
	}

	this.deferredImportSelectorHandler.process();
}

由于我们的配置类是加了@Configuration注解类,所以会被解析成AnnotatedBeanDefinition,所以会进入第一个if判断,会执行parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());,具体的代码如下:

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
	processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
}

继续调用processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);方法,具体的代码如下:

protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
	//判断是否需要跳过
    if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
		return;
	}

    //判断解析类是否存在过
	ConfigurationClass existingClass = this.configurationClasses.get(configClass);
	if (existingClass != null) {
        //两个都是importedBy属性不会空,直接合并
		if (configClass.isImported()) {
			if (existingClass.isImported()) {
				existingClass.mergeImportedBy(configClass);
			}
			// Otherwise ignore new imported config class; existing non-imported class overrides it.
			return;
		}
		else {
			// Explicit bean definition found, probably replacing an import.
			// Let's remove the old one and go with the new one.
			this.configurationClasses.remove(configClass);
			this.knownSuperclasses.values().removeIf(configClass::equals);
		}
	}

	// Recursively process the configuration class and its superclass hierarchy.
    // 将configClass 转换成 sourceClass
	SourceClass sourceClass = asSourceClass(configClass, filter);
	do {
        //递归处理配置类以及配置类的超类
		sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
	}
	while (sourceClass != null);

    //将解析过的配置类放入到对应configurationClasses
	this.configurationClasses.put(configClass, configClass);
}

上面的代码我们只需要看最重要的解析的方法doProcessConfigurationClass(configClass, sourceClass, filter);,具体的代码如下:

protected final SourceClass doProcessConfigurationClass(
		ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
		throws IOException {

	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
        //首先递归处理任何成员(嵌套)类
        //这儿我们没有所有不用管
		processMemberClasses(configClass, sourceClass, filter);
	}

	// Process any @PropertySource annotations
    // 处理任何@PropertySource注解
	for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), PropertySources.class,
			org.springframework.context.annotation.PropertySource.class)) {
		if (this.environment instanceof ConfigurableEnvironment) {
			processPropertySource(propertySource);
		}
		else {
			logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
					"]. Reason: Environment must implement ConfigurableEnvironment");
		}
	}

	// Process any @ComponentScan annotations
    //解析 @ComponentScan注解,前面讲过,主要是将@ComponentScan注解中配置的路径下的类解析成BeanDefinition
    //取出ComponentScan注解中的数据
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
    //判断是不是为空
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
       	//遍历所有的@ComponentScan注解
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
            //解析@ComponentScan
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
             //遍历所有的扫描出来的BeanDefinition
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                 //获取BeanDefinition的原始类
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                 //一般取出来是空的
				if (bdCand == null) {
                      //设置为对应BeanDefinition
					bdCand = holder.getBeanDefinition();
				}
                 //判断是不是配置类,是配置类再次解析一遍,和前面的逻辑是一样的。
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	// Process any @Import annotations
    // 解析 @Import注解 也是今天这篇博客的重点
	processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

	// Process any @ImportResource annotations
    // 解析 @ImportResource 注解,后面博客会讲
	AnnotationAttributes importResource =
			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
	if (importResource != null) {
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
   	// 处理单个@Bean的方法,只是将加了@Bean的注解的方法包装成BeanMethod添加到configClass中beanMethods的set集合中
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
    // 处理默认的接口方法
	processInterfaces(configClass, sourceClass);

	// Process superclass, if any
    // 处理超类 如果有
	if (sourceClass.getMetadata().hasSuperClass()) {
		String superclass = sourceClass.getMetadata().getSuperClassName();
		if (superclass != null && !superclass.startsWith("java") &&
				!this.knownSuperclasses.containsKey(superclass)) {
			this.knownSuperclasses.put(superclass, configClass);
			// Superclass found, return its annotation metadata and recurse
			return sourceClass.getSuperClass();
		}
	}

	// No superclass -> processing is complete
    // 如果没有超类,表示处理完成
	return null;
}

上次讲扫描机制的时候,同时也讲到了@ComponentScan注解的解析,当时笔者只讲了怎么将配置类中的@ComponentScan中定义的扫描路径中的类解析成BeanDefinition,这个时候BeanDefinition的集合,又遍历一次,如果是配置类,会再解析一遍。也就是如果你的@Bean注解方法所在类不是最早注册的配置类,而是通过扫描出来的,这个时候这个类中@Bean注解也是会解析的。

有点跑题了,这个时候继续讲我们这篇博客的重点,当我们打开@MapperScan注解的时候,发现其中加了一个@Import注解,所以我们要看processImports(configClass, sourceClass, getImports(sourceClass), filter, true);具体的代码如下,其中getImports(sourceClass)方法就是递归调用所有的注解,取出对应加了@Import注解中value的值,同时放入Collection集合中,这儿取出来的就是MapperScannerRegistrar

private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
		Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
		boolean checkForCircularImports) {

    //判断传进来的刚刚通过getImport方法解析出来的集合是不是为空。
	if (importCandidates.isEmpty()) {
		return;
	}

    //checkForCircularImports判断是不是环形的引入的 这儿是true
    //isChainedImportOnStack(configClass)判断是不是在importStack集合中 表示出现了环形引入的问题
	if (checkForCircularImports && isChainedImportOnStack(configClass)) {
		this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
	}
	else {
        //将这个configClass 放到importStack中去
		this.importStack.push(configClass);
		try {
            //遍历Import的集合
			for (SourceClass candidate : importCandidates) {
                //判断有没有实现ImportSelector接口,这儿是没有的
				if (candidate.isAssignable(ImportSelector.class)) {
					// Candidate class is an ImportSelector -> delegate to it to determine imports
					Class<?> candidateClass = candidate.loadClass();
					ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
							this.environment, this.resourceLoader, this.registry);
					Predicate<String> selectorFilter = selector.getExclusionFilter();
					if (selectorFilter != null) {
						exclusionFilter = exclusionFilter.or(selectorFilter);
					}
					if (selector instanceof DeferredImportSelector) {
						this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
					}
					else {
						String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
						Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
						processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
					}
				}
                //判断有没有实现ImportBeanDefinitionRegistrar接口,MapperScannerRegistrar实现了ImportBeanDefinitionRegistrar
				else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
					// Candidate class is an ImportBeanDefinitionRegistrar ->
					// delegate to it to register additional bean definitions
                      //获取 MapperScannerRegistrar 的class类
					Class<?> candidateClass = candidate.loadClass();
                      // 实例化MapperScannerRegistrar类
					ImportBeanDefinitionRegistrar registrar =
							ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
									this.environment, this.resourceLoader, this.registry);
                      // 将这个实例化好的MapperScannerRegistrar类放到configClass中importBeanDefinitionRegistrars的Map属性中去
					configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
				}
				else {
					// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
					// process it as an @Configuration class
                      // 如果不是ImportSelector和ImportBeanDefinitionRegistrar类直接将这个类当成@Configuration 的类来处理
					this.importStack.registerImport(
							currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
					processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
				}
			}
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanDefinitionStoreException(
					"Failed to process import candidates for configuration class [" +
					configClass.getMetadata().getClassName() + "]", ex);
		}
		finally {
            //最后从栈中弹出这个类
			this.importStack.pop();
		}
	}
}

上面的方法就是将@Import中引入的类创建出来,最后添加到configClassimportBeanDefinitionRegistrars的Map属性中去,至此我们知道这个类是怎么什么时候添加到spring的容器中去。在此笔者录了一个GIF给读者查看,便于读者的理解,具体的如下:

Spring源码系列(九)MapperScan注解的原理(一)

那么什么时候调用其中的方法呢?我们继续回到原来的方法。具体的代码如下:

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
	// Parse each @Configuration class
    // 解析配置类 创建一个解析对象,前面的博客我们有讲过
	ConfigurationClassParser parser = new ConfigurationClassParser(
			this.metadataReaderFactory, this.problemReporter, this.environment,
			this.resourceLoader, this.componentScanBeanNameGenerator, registry);

    //将配置类的BeanDefinition存入到set集合中去
	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    //已经解析过的BeanDefinition
	Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
	do {
        //解析配置类,前面的博客我们已经讲过了
		parser.parse(candidates);
        //校验
		parser.validate();

        //获取的解析配置类
		Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
        //从解析的配置类中移除所以已经解析的配置类
		configClasses.removeAll(alreadyParsed);

		// Read the model and create bean definitions based on its content
        // 创建reader对象
		if (this.reader == null) {
			this.reader = new ConfigurationClassBeanDefinitionReader(
					registry, this.sourceExtractor, this.resourceLoader, this.environment,
					this.importBeanNameGenerator, parser.getImportRegistry());
		}
        //加载一些新的BeanDefinition
		this.reader.loadBeanDefinitions(configClasses);
		alreadyParsed.addAll(configClasses);

		candidates.clear();
        //看新添加进来的BeanDefinition是否有配置类,如果有配置类会继续解析。
		if (registry.getBeanDefinitionCount() > candidateNames.length) {
			String[] newCandidateNames = registry.getBeanDefinitionNames();
			Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
			Set<String> alreadyParsedClasses = new HashSet<>();
			for (ConfigurationClass configurationClass : alreadyParsed) {
				alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
			}
			for (String candidateName : newCandidateNames) {
				if (!oldCandidateNames.contains(candidateName)) {
					BeanDefinition bd = registry.getBeanDefinition(candidateName);
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
							!alreadyParsedClasses.contains(bd.getBeanClassName())) {
						candidates.add(new BeanDefinitionHolder(bd, candidateName));
					}
				}
			}
			candidateNames = newCandidateNames;
		}
	}
	while (!candidates.isEmpty());

	// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
    // 将ImportRegistry注册为Bean,以支持ImportAware @Configuration类
	if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
		sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
	}

	if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
		// Clear cache in externally provided MetadataReaderFactory; this is a no-op
		// for a shared cache since it'll be cleared by the ApplicationContext.
		((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
	}
}	

上面的代码在注释中已经解释的很清楚了,而加了@Import注解的value中的类的MapperScannerRegistrarregisterBeanDefinitions方法就是在this.reader.loadBeanDefinitions(configClasses);方法中调用的具体的代码如下:

public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
	TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
    //遍历所有的配置类,然后加载BeanDefinition
	for (ConfigurationClass configClass : configurationModel) {
		loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
	}
}

这个时候我们需要看下loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);,具体的代码如下:

private void loadBeanDefinitionsForConfigurationClass(
		ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {

    //判断是否跳过,理论上是不会执行
	if (trackedConditionEvaluator.shouldSkip(configClass)) {
		String beanName = configClass.getBeanName();
		if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
			this.registry.removeBeanDefinition(beanName);
		}
		this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
		return;
	}

    //判断配置类中importedBy的属性是不是空,这儿是空的
	if (configClass.isImported()) {
		registerBeanDefinitionForImportedConfigurationClass(configClass);
	}
    //遍历所有的@Bean的方法,进行对应的注册成BeanDefinition
	for (BeanMethod beanMethod : configClass.getBeanMethods()) {
		loadBeanDefinitionsForBeanMethod(beanMethod);
	}

    //处理@ImportResource中引入的类,将其转换成BeanDefinition
	loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
    //处理@Import中引入的类,将其转换成BeanDefinition
	loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}

由于我们使用了@Bean的注解,对对应的方法进行了注解,所以这儿注解BeanDefinition还是简单的讲下,比较简单。主要是通过loadBeanDefinitionsForBeanMethod(beanMethod);方法执行的。具体的代码如下:

private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    //获取配置类
	ConfigurationClass configClass = beanMethod.getConfigurationClass();
    //获取方法的元数据
	MethodMetadata metadata = beanMethod.getMetadata();
    //获取方法名
	String methodName = metadata.getMethodName();

	// Do we need to mark the bean as skipped by its condition?
    // 我们是否需要将bean标记为被其条件跳过?
	if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
		configClass.skippedBeanMethods.add(methodName);
		return;
	}
	if (configClass.skippedBeanMethods.contains(methodName)) {
		return;
	}

    //获取方法上@Bean注解中的数据
	AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
	Assert.state(bean != null, "No @Bean annotation attributes");

	// Consider name and any aliases
    // 获取@Bean中的name的属性
	List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
    // 如果不为空去第一个,如果为空取方法名
	String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

	// Register aliases even when overridden
    // 将取出来的name的属性除了第一个剩下全部设置成为别名
	for (String alias : names) {
		this.registry.registerAlias(beanName, alias);
	}

	// Has this effectively been overridden before (e.g. via XML)?
    //判断xml中是否已经配置过了
	if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
		if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
			throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
					beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
					"' clashes with bean name for containing configuration class; please make those names unique!");
		}
		return;
	}

    //创建对应的BeanDefinition,博客中有讲过什么Bean对应什么BeanDefinition
	ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata, beanName);
    //设置源
	beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

    //判断是否是静态的方法
	if (metadata.isStatic()) {
		// static @Bean method
		if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {
			beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());
		}
		else {
			beanDef.setBeanClassName(configClass.getMetadata().getClassName());
		}
		beanDef.setUniqueFactoryMethodName(methodName);
	}
	else {
		// instance @Bean method
		beanDef.setFactoryBeanName(configClass.getBeanName());
		beanDef.setUniqueFactoryMethodName(methodName);
	}

	if (metadata instanceof StandardMethodMetadata) {
		beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());
	}

    //设置自动装配的模型为构造器注入
	beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    //设置跳过属性为true
	beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.
			SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

    //处理一些通用的注解 Lazy Primary DependsOn Role Description
	AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

    //获取注解@Bean中定义的autowire 自动装配模型
	Autowire autowire = bean.getEnum("autowire");
    //判断是不是 byname 或者 bytype,如果是才会设置
	if (autowire.isAutowire()) {
		beanDef.setAutowireMode(autowire.value());
	}

    //获取autowireCandidate属性,自动装配的候选对象
	boolean autowireCandidate = bean.getBoolean("autowireCandidate");
	if (!autowireCandidate) {
		beanDef.setAutowireCandidate(false);
	}

    //获取 initMethod
	String initMethodName = bean.getString("initMethod");
	if (StringUtils.hasText(initMethodName)) {
		beanDef.setInitMethodName(initMethodName);
	}

    // 获取 destroyMethod
	String destroyMethodName = bean.getString("destroyMethod");
	beanDef.setDestroyMethodName(destroyMethodName);

	// Consider scoping
    // 处理范围
	ScopedProxyMode proxyMode = ScopedProxyMode.NO;
	AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
	if (attributes != null) {
		beanDef.setScope(attributes.getString("value"));
		proxyMode = attributes.getEnum("proxyMode");
		if (proxyMode == ScopedProxyMode.DEFAULT) {
			proxyMode = ScopedProxyMode.NO;
		}
	}

	// Replace the original bean definition with the target one, if necessary
	BeanDefinition beanDefToRegister = beanDef;
	if (proxyMode != ScopedProxyMode.NO) {
		BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
				new BeanDefinitionHolder(beanDef, beanName), this.registry,
				proxyMode == ScopedProxyMode.TARGET_CLASS);
		beanDefToRegister = new ConfigurationClassBeanDefinition(
				(RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, beanName);
	}

	if (logger.isTraceEnabled()) {
		logger.trace(String.format("Registering bean definition for @Bean method %s.%s()",
				configClass.getMetadata().getClassName(), beanName));
	}
    //最后注册到BeanDefinition的map中去。
	this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

上面的代码大概就是将@Bean的方法解析成一个BeanDefinition,然后注册到IOC容器中的BeanDefinition的Map中去。看完了这个,我们要看loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());方法,这个方法处理@Import中引入的类,将其转换成BeanDefinition,具体的代码如下:

private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
	registrars.forEach((registrar, metadata) ->
			registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator));
}

上面的代码是lambda表达式,就是遍历之前所有通过@Import引入进来的Class,只不过这个Class实例化了,但是没有被转成BeanDefinition存入到容器中去,这个转换成BeanDefinition的代码是在MapperScannerRegistrar中的registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法中。由于篇幅的原因,笔者决定在下篇博客中会讲。

笔者打算本篇博客将MapperScan注解的原理给讲完,但是由于篇幅的原因,笔者就讲了如何调用到MapperScannerRegistrar中的registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)方法。至于这个方法干了什么事,笔者下篇博客会讲清楚。

Spring源码系列(九)MapperScan注解的原理(一)相关教程

  1. springboot连接达梦数据库

    springboot连接达梦数据库 springboot连接达梦数据库 这次实战主要说springboot项目连接达梦数据库。 先准备好达梦数据库的驱动包,如下: 在执行maven命令把该驱动包安装到自己的maven仓库,命令如下: mvn install:install-file -DgroupId=com.dm -Dartifac

  2. springboot整合shiro

    springboot整合shiro 1.整合SpringBoot项目实战 1.0整合思路 1.1 创建springboot项目 1.2 引入依赖 !--引入jsp解析依赖--dependency groupIdorg.apache.tomcat.embed/groupId artifactIdtomcat-embed-jasper/artifactId/dependencydependency groupIdjstl/gro

  3. Spring_Bean之间的关系

    Spring_Bean之间的关系 Spring_Bean之间的关系:继承;依赖 继承Bean配置 Spring允许继承bean的配置,被继承的bean称为父bean,继承这个父Bean的Bean称为子Bean 子Bean从父Bean中继承配置,包括Bean的属性配置 子Bean也可以覆盖从父Bean继承过来的配置 配置文

  4. docker+kubernetes+springcloud微服务集群部署,spring-cloud-ku

    docker+kubernetes+springcloud微服务集群部署,spring-cloud-kubernetes,使用k8s部署spring cloud并实现服务注册、负载均衡、网关等功能 docker+kubernetes+springcloud微服务集群部署,spring-cloud-kubernetes,使用k8s部署spring cloud并实现服务注册、

  5. 关于SSM事务无法回滚问题之will not be managed by Spring

    关于SSM事务无法回滚问题之will not be managed by Spring 关于SSM事务无法回滚问题之will not be managed by Spring (此文写于本人刚开始学习SSM框架,如有不对的地方欢迎留言指导) 正文 问题分析 正文 如题所述,我在练习使用SSM框架时遇到的问题: ( 如

  6. 深入底层源码,解析Mybatis的会话机制

    深入底层源码,解析Mybatis的会话机制 点关注,不迷路;持续更新Java相关技术及资讯!!! 在同一个方法中,Mybatis多次请求数据库,是否要创建多个SqlSession会话? 可能最近撸多了,当时脑子里一片模糊,眼神迷离,虽然我当时回答他:如果多个请求同一个事

  7. Day25SSM之SpringMVC拦截器案例***

    Day25SSM之SpringMVC拦截器案例*** 案例分析 京东的某些功能,必须登录才能访问 没有登录,必须登录 订单 ,地址 案例实现 //1:判断一下路径,如果访问的是order address..判断是否登录 未登录强制到登入页面public class LoginInterceptor implements Handle

  8. springboot与mybatis入门

    springboot与mybatis入门 文章目录 在这个项目使用许多非常重要的注解 1.导入相关包 2.在配置文件中添加mybatis配置 3.简单项目实现 3.1添加数据库 3.2 编写实体类 User 3.3实现mybatis接口绑定技术(编写mapper和映射的xml) userMapper userMapper.xml 3.4