转载

Spring源码解析系列二:Spring初始化准备处理器过程

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

2.点击 AnnotationConfigApplicationContext

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

初始化 AnnotationConfigApplicationContext 这个类之前会首先初始化话其父类,

AnnotationConfigApplicationContext ` 的父类为 GenericApplicationContext

3.查看 GenericApplicationContext

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

DefaultListableBeanFactory 就是我们的 Bean工厂类

通过查看 GenericApplicationContext 的默认构造方法发现,我们的神奇的Bean工厂是在这里被初始化的

4.回到 AnnotationConfigApplicationContext

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

查看 AnnotationConfigApplicationContext 默认的构造方法,初始化了读取器 AnnotatedBeanDefinitionReader ,准备处理器的功能就在这个类中,至于 ClassPathBeanDefinitionScanner 对于注解开发来说,似乎没有什么作用.

5.点击 AnnotatedBeanDefinitionReader

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

这里没有做什么,调用另一个构造方法 通过参数 BeanDefinitionRegistry ,我们可以发现 AnnotationConfigApplicationContext 对象,其实就是一个注册器 此时的 registry 实质就是 AnnotationConfigApplicationContext 对象

6.点击 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.点击 registerAnnotationConfigProcessors

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

8.点击 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.点击 registerPostProcessor 方法

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 点击 registerBeanDefinition

我们选择 DefaultListableBeanFactory 这个类,注意类就是开篇所说的 工厂类

@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);
		}
	}
复制代码

this.beanDefinitionMap.put(beanName, beanDefinition); 中把 处理器的描述类添加进 beanDefinitionMap 集合中

到了这里Spring 就把需要的处理器添加进Spring工厂啦

视频讲解:

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

视频为自己学习的时候录制的,也方便自己以后看

Spring5源码地址:

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

Spring5源码都是已经构建好的了,无需再使用gradle进行构建了,直接打开就可以跑起来

原文  https://juejin.im/post/5dec8ca0518825125e1ba728
正文到此结束
Loading...