Spring source parsing Series II: Spring processor initialization preparation process

Today is the second article in the Spring series, come on!

1. Create a test class

public class Test01 {
	public static void main(String[] args) {
		//这个构造方法会把Spring所有的环境都准备好
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
	}
}
复制代码

2. Click AnnotationConfigApplicationContext

	public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		//这个类有父类,所以会先初始化父类的构造方法,接着初始化自己的构造方法
		//调用无参构造方法进行初始化一个读取器和扫描仪
		this();
		//把配置类加载进 DefaultListableBeanFactory 的map集合中
		//配置类可以一次性传多个,这个方法执行后,只是把配置类加载进了 DefaultListAbleBeanFactory的map集合中
		//还没有扫描其他的的加了组件的类
		register(annotatedClasses);
		//实例化所有被加了组件的对象
		refresh();
	}
复制代码

Initialization AnnotationConfigApplicationContextwill first initialize the words of its parent class before the class,

AnnotationConfigApplicationContext `Parent is GenericApplicationContext

3. Review GenericApplicationContext

public GenericApplicationContext() {
   //实例化工厂
   this.beanFactory = new DefaultListableBeanFactory();
}
复制代码

DefaultListableBeanFactory Bean is our factory class

By looking at GenericApplicationContextthe default constructor we found our magic Bean plant is here initialized

4. Go back AnnotationConfigApplicationContext

	public AnnotationConfigApplicationContext() {
		//创建一个读取被加了注解的bean读取器  ,当前对象传过去
		this.reader = new AnnotatedBeanDefinitionReader(this);
		/**
		 * 可以用来扫描包来转换成beanDefinition
		 * 但是Spring扫描包不是使用这个对象,而是使用ClassPathBeanDefinitionScanner
		 * 这里的scanner仅仅是为了用户之间能够使用 AnnotationConfigApplicationContext对象的scan()方法
		 * 如果用户没有自己手动调用的话,其实是没有扫描作用的
		 */
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}
复制代码

View AnnotationConfigApplicationContextthe default constructor to initialize the reader AnnotatedBeanDefinitionReader, prepare function of the processor in this class, as ClassPathBeanDefinitionScannerfor the development of notes, it seems no effect.

5. Click AnnotatedBeanDefinitionReader

	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
		this(registry, getOrCreateEnvironment(registry));
	}
复制代码

Here's what not to do, call another constructor parameter BeanDefinitionRegistry, we can find AnnotationConfigApplicationContextthe object, in fact, a registrar at this time of the registryessence AnnotationConfigApplicationContextobjects

6. Click this

	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		//把AnnotationConfigApplicationContext对象赋值给当前类的 registry
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
复制代码

7. Click registerAnnotationConfigProcessors

	public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
		//同样的构造方法名,参数列表不一样
		registerAnnotationConfigProcessors(registry, null);
	}
复制代码

8. Click registerAnnotationConfigProcessors

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		//通过registry,获取beanFactory工厂对象
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
				//添加排序对象 AnnotationAwareOrderComparator
				if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
					beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
				}
			//提供延迟加载的功能ContextAnnotationAutowireCandidateResolver
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}
         //BeanDefinitionHolder 里面有一个beanName 和 beanDefinition 属性方便传参数
		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

		/**
		 * 问个问题?为啥要注册这个ConfigurationClassPostProcessor类到工厂的map集合中呢?
		 * 以后文章解析!
		 */

     //判断整个环境中时候存在了这个常量
    //org.springframework.context.annotation.internalConfigurationAnnotationProcessor
	//CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME 会被作为beanName
    
      //(1)把处理 ConfigurationClassPostProcessor的描述类 添加进 工厂
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

       //(2)把处理 AutowiredAnnotationBeanPostProcessor 的描述类 添加进 工厂
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

      //(3)把处理 CommonAnnotationBeanPostProcessor 的描述类 添加进 工厂
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

      //(4)把处理 EventListenerMethodProcessor 的描述类 添加进 工厂
		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

      //(5)把处理 DefaultEventListenerFactory 的描述类 添加进 工厂
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}
    
         //在reader这个过程当中,这个返回值不会起任何作用
		return beanDefs;
	}
复制代码

9. Click registerPostProcessormethod

	private static BeanDefinitionHolder registerPostProcessor(
			BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
       //ROLE_INFRASTRUCTURE=2 代表是Spring内部的类,  ROLE_SUPPORT = 1;代表的是用户的类
		definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);

		//此时的beanName为就是Spring自己定义的常量字符串
		//这个方法就是把  内部类definition存储到 beanDefinitionMap中
		registry.registerBeanDefinition(beanName, definition);
		return new BeanDefinitionHolder(definition, beanName);
	}
复制代码

10.Ctrl + Alt + B Click registerBeanDefinition

We chose DefaultListableBeanFactorythis class, the class is to be noted that the opening of the factory said class

@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {

		Assert.hasText(beanName, "Bean name must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				if (logger.isInfoEnabled()) {
					logger.info("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							existingDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(existingDefinition)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					removeManualSingletonName(beanName);
				}
			}
			else {
		//在这个方法中就把 beanDefinition 存储在 DefaultListableBeanFactory的map集合中
		//顾名思义,beanDefinitionMap就是一个存储beanDefinition的map集合
		//在这个集合当中还有Spring当中本身已经初始好的对象
				this.beanDefinitionMap.put(beanName, beanDefinition);
				//把beanName存储在这个list集合中
				this.beanDefinitionNames.add(beanName);
				//这个是去重的,不是重点
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}
复制代码

In this.beanDefinitionMap.put(beanName, beanDefinition);the description of the processor-based add beanDefinitionMapset

Spring put here to the processor needs to add it into the Spring factory

Video Tutorial:

<https://www.bilibili.com/video/av67899876?p=3>

Video recording time for their own learning, but also facilitate their future look

Spring5 Source Address:

<https://gitee.com/zouchangfu/spring_5_source_code>

Spring5 are already built a good source, and no longer need to use to build a gradle, directly open can run up

Written in the last:

A sophomore, is not easy to squeeze time to write a blog, read easily point a praise, praise your point is my greatest encouragement

Guess you like

Origin juejin.im/post/5dec8ca0518825125e1ba728