欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringFramework源码分析(2):IoC容器AnnotationConfigApplicationContext的创建

程序员文章站 2022-06-14 22:02:08
1 一点建议我们在看源码的时候,不应该上来直接就开始读,在对作者的设计意图没有一丁点了解的情况下读源码,就是个从入门到放弃的过程,读完了也不知道到底在干嘛。这里给出一点个人的建议,在阅读源码前,我们需要先弄清楚一个组件或框架的整体流程是什么样子的,如果让我们来实现同样的功能,我们该如何思考以及从哪里下手。读Spring源码前,可以先看下Spring中重要的类有哪些,先有个大体概念与印象,可参考https://blog.csdn.net/sodawoods/article/details/107240123...

1 一点建议

我们在看源码的时候,不应该上来直接就开始读,在对作者的设计意图没有一丁点了解的情况下读源码,就是个从入门到放弃的过程,读完了也不知道到底在干嘛。这里给出一点个人的建议,在阅读源码前,我们需要先弄清楚一个组件或框架的整体流程是什么样子的,如果让我们来实现同样的功能,我们该如何思考以及从哪里下手。读Spring源码前,可以先看下Spring中重要的类有哪些,先有个大体概念与印象,可参考https://blog.csdn.net/sodawoods/article/details/107240123
另外,需要把源码下载下来,使用debug进行调试。
最后,Spring的源码相对较难,需要静下心来阅读。

2 自己写一个IoC容器?

我们在使用Spring IoC容器时,目前主要会使用基于注解的方式。通常会定义一些POJO,然后定义一下配置信息,例如注解和Java代码。如果让我们自己实现一个IoC的容器,那我们的大体思路应该首先找到配置类,然后解析这个配置类,这个配置类上应该会标注@Configuration、@ComponentScan、@Import等注解,类中的方法可能会标注@Bean注解。我们需要处理这些注解,把这个配置类中定义的实例给初始化出来,并且还需要给实例注入相应的属性(或者说是依赖),这个步骤应该会用到反射。另外,对于单实例的实例,我们把它们保存起来,例如保存在一个Map中,每次需要的时候直接从这个Map中取。对于多实例的对象,每次新创建一个。

https://blog.csdn.net/sodawoods/article/details/107240123中,我们定义了A和B两个POJO,在配置类AppConfig中,我们告诉Spring容器要加入两个Bean,名字分别是a和b,并且a是lazy的,并且dependsOn b,也就是说在初始化a之前需要先先初始化b。b的scope被定义成了prototype,即每次从容器中getBean的时候,会新生成一个Bean。之后,我们将AppConfig传入了AnnotationConfigApplicationContext的构造方法,Spring自动帮我们生成了一个IoC容器,我们后续就可以直接从容器中获取Bean了。可以看到,Spring通过下面这一行代码就帮我们完成了IoC容器的创建,那这行代码中到底做了哪些事情呢?我们接着往下看。

AnnotationConfigApplicationContext configApplicationContext =
				new AnnotationConfigApplicationContext(AppConfig.class);

3 Spring IoC容器的创建流程

我们在第2小节分析了实现一个IoC容器的大致过程,Spring的IoC容器的实现过程是类似的,不过比我们考虑的更加周全。我们可以从new AnnotationConfigApplicationContext(AppConfig.class)入手,看Spring是怎么一步步得到IoC容器的。
我们初始化AnnotationConfigApplicationContext时,调用的构造方法中依次调用了this()、register(componentClasses)以及refresh()方法,接下来我们逐一进行讲解。

/**
	 * Create a new AnnotationConfigApplicationContext, deriving bean definitions
	 * from the given component classes and automatically refreshing the context.
	 * @param componentClasses one or more component classes — for example,
	 * {@link Configuration @Configuration} classes
	 */
	public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
		/*
		* 注意,有父类的情况下先调用父类的构造方法
		* 进一步讲,有父类的情况下调用顺序为,
		* 父类的静态代码块(即父类执行类初始化clinit方法),子类静态代码块(clinit方法),父类非静态代码块,父类构造方法,子类非静态代码块,子类构造方法
		* */
		this();
		register(componentClasses);
		refresh();
	}

3.1 this()方法

1 调用父类构造方法

如果一个类有父类,则在调用子类的构造方法前,会先调用其父类的构造方法,这一点我们在看源码时可能会忽略掉,因此需要注意一下。
由于AnnotationConfigApplicationContext依次继承了GenericApplicationContext、AbstractApplicationContext和DefaultResourceLoader,因此在执行this方法之前,实际上会先依次执行以下的构造方法。可以看到,通过调用父类的构造方法,我们的AnnotationConfigApplicationContext中已经有用于Resource加载的resourcePatternResolver对象和BeanFactory的实现类DefaultListableBeanFactory了。

// 调用的第1个构造方法
public DefaultResourceLoader() {
}

// 调用的第2个构造方法
public AbstractApplicationContext() {
		/*
		* Spring的Resource接口是比java.net.URL更加强大的用来对底层资源进行访问的接口
		*  Resource的加载器,从Resource Location获取到Resource,Resource Location例如file:C:/test.dat、classpath:test.dat
		* */
		this.resourcePatternResolver = getResourcePatternResolver();
}

// 3 调用的第3个构造方法,可以看到AnnotationConfigApplicationContext中使用的BeanFactory的实现是DefaultListableBeanFactory
public GenericApplicationContext() {
		this.beanFactory = new DefaultListableBeanFactory();
}

2 调用ApplicationConfigAnnotationContext自己的构造方法

调用ApplicationConfigAnnotationContext自己的构造方法后,我们可以得到AnnotatedBeanDefinitionReader对象(用于读取标注了注解的BeanDefinition)以及ClassPathBeanDefinitionScanner对象(用户手动调用ApplicationConfigAnnotationContext#scan()方法时,通过该scanner对象就行扫描)

/**
	 * 在调用自己的构造方法之前,会先调用父类的构造方法,并且在调用父类的构造方法之前,会先初始化final和static的属性以及静态代码块
	 * 在GenericApplicationContext中,进行了BeanFactory的初始化this.beanFactory = new DefaultListableBeanFactory();
	 * 看类图的时候,如果是一个类,那么它的所有的父类的构造方法都会从上到下被调用一遍
	 *
	 * Create a new AnnotationConfigApplicationContext that needs to be populated
	 * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
	 */
	public AnnotationConfigApplicationContext() {
		/*
		* AnnotatedBeanDefinitionReader本身读取一个类,将这个类转化成BeanDefination存储到BeanDefinationMap中。
		*
		*  在父类中已经新建了一个DefaultListableBeanFactory,
		*  AnnotatedBeanDefinitionReader会向DefaultListableBeanFactory的BeanDefinationMap中添加一些
		*  与注解相关的post processor,也就是将一些PostProcessor转化成BeanDefination然后加入到BeanDefinationMap中
		*
		* 具体来讲,初始化AnnotatedBeanDefinitionReader的时候,
		* 会向BeanFactory中添加一个BeanDefinitionRegistryPostProcessor的BeanDefinition(ConfigurationClassPostProcessor),ConfigurationClassPostProcessor会在AbstractApplicationContext#invokeBeanFactoryPostProcessors方法中用到,解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
		* 和其他4到5个BeanPostProcessor的BeanDefinition(注意是BeanDefinition而不是Bean),包括
		*   AutowiredAnnotationBeanPostProcessor
		* 	CommonAnnotationBeanPostProcessor(处理JSR250,例如@PostConstruct @PreDestroy)
		*	PersistenceAnnotationBeanPostProcessor(处理JPA java persistence API)
		*	EventListenerMethodProcessor
		*	DefaultEventListenerFactory
		* */
		this.reader = new AnnotatedBeanDefinitionReader(this);

		/*
		* 扫描包或类并转化成BeanDefination。
		* 注意,只有程序员自己在使用AnnotationConfigApplicationContext.scan()方法时,才会用到这个scanner
		* 但实际上,我们的扫描工作不是这个scanner完成的,而是spring自己new的一个ClassPathBeanDefinitionScanner
		* */
		this.scanner = new ClassPathBeanDefinitionScanner(this);
}

2.1 AnnotatedBeanDefinitionReader的初始化

首先是AnnotatedBeanDefinitionReader的构造方法,我们主要看一下向DefaultListableBeanFactory中添加BeanDefinition的方法。


// 1 AnnotationConfigApplicationContext实现了BeanDefinitionRegistry接口,因此这里直接传入了this
this.reader = new AnnotatedBeanDefinitionReader(this);

/**
	 * Register all relevant annotation post processors in the given registry.
	 * @param registry the registry to operate on
	 * @param source the configuration source element (already extracted)
	 * that this registration was triggered from. May be {@code null}.
	 * @return a Set of BeanDefinitionHolders, containing all bean definitions
	 * that have actually been registered by this call
	 */
	public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			// ConfigurationClassPostProcessor是一个BeanDefinitionRegistryPostProcessor,也是BeanFactoryPostProcessor
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 下面注册的都是BeanPostProcessor
		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));
		}

		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		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));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		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));
		}

		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));
		}

		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));
		}

		return beanDefs;
}

2.2 ClassPathBeanDefinitionScanner的初始化

注意这里的ClassPathBeanDefinitionScanner只是在用户调用
AnnotationConfigApplicationContext#scan()方法时才会使用。

3.2 register(componentClasses)方法

这个方法比较简单,通过2.1节new出来的AnnotatedBeanDefinitionReader将传入的每个componentClass实例化成AnnotatedGenericBeanDefinition,然后保存到DefaultListableBeanFactory的beanDefinitionMap中。注意只是将类信息转化成了BeanDefinition并添加到了BeanFactory中,并没有实例化Bean。

3.3 refresh()方法

refresh()方法是完成类扫描、转化成BeanDefinition、实例化成Bean、对Bean进行依赖注入以及执行BeanFactoryPostProcessor、BeanPostProcessor、ApplicationListener的核心方法。refresh方法的整体流程是首先进行一些准备,执行BeanFactoryPostProcessor的方法、添加的BeanPostProcessor对应的Bean实例、初始化MessageSource、初始化多播器、注册Listener、最后将BeanFactory中单实例的BeanDefinition转化成Bean实例并完成属性注入与装配。
refresh方法中最重要的几个方法分别是invokeBeanFactoryPostProcessors、registerBeanPostProcessors、finishBeanFactoryInitialization(beanFactory)。
下面我们分析下每个方法。

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			// 设置startupDate、closed、active的值,初始化earlyApplicationListeners earlyApplicationEvents
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			// AnnotationConfigApplicationContext是不允许重复调用refresh方法的,如果重复调用,在obtainFreshBeanFactory()中会抛错
			// obtainFreshBeanFactory返回的BeanFactory就是之前new的DefaultListableBeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				// 该方法留给子类实现
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				// 执行用户自定义和Spring提供的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,
				// 其中通过ConfigurationClassPostProcessor会完成类扫描,转化成BeanDefinition;如果一个类标注了@Configuration,则会被cglib增强
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				// 因为BeanPostProcessor对应的Bean在registerBeanPostProcessors()已经变成了Bean,所以这里说的是实例化剩余的非lazy的单例
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

1 prepareRefresh()

为ApplicationContext的refresh做一些准备工作,例如设置一些变量值、注册earlyApplicationListeners(默认是空集合)。

/**
	 * Prepare this context for refreshing, setting its startup date and
	 * active flag as well as performing any initialization of property sources.
	 */
	protected void prepareRefresh() {
		// Switch to active.
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		this.active.set(true);

		if (logger.isDebugEnabled()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Refreshing " + this);
			}
			else {
				logger.debug("Refreshing " + getDisplayName());
			}
		}

		// Initialize any placeholder property sources in the context environment.
		initPropertySources();

		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
		getEnvironment().validateRequiredProperties();

		// Store pre-refresh ApplicationListeners...
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
			// Reset local application listeners to pre-refresh state.
			this.applicationListeners.clear();
			this.applicationListeners.addAll(this.earlyApplicationListeners);
		}

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

2 obtainFreshBeanFactory

刷新BeanFactory。对于AnnotationConfigApplicationContext来说,该方法会直接返回上面的DefaultListableBeanFactory。
此外,AnnotationConfigApplicationContext是不允许重复调用refresh方法的,如果重复调用,在obtainFreshBeanFactory()中会抛错。

/**
	 * Tell the subclass to refresh the internal bean factory.
	 * @return the fresh BeanFactory instance
	 * @see #refreshBeanFactory()
	 * @see #getBeanFactory()
	 */
	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		return getBeanFactory();
	}

3 prepareBeanFactory(beanFactory)

这个方法向BeanFactory的beanPostProcessors集合中添加了两个BeanPostProcessor实例(注意不是BeanDefinition), 分别是ApplicationContextAwareProcessor和ApplicationListenerDetector。
之后,向DefaultSingletonBeanRegistry的单例池singletonObjects中添加三个单例,分别是environment、systemProperties和systemEnvironment。

/**
	 * 这个方法向BeanFactory的beanPostProcessors集合中添加了两个BeanPostProcessor实例(注意不是BeanDefinition),
	 * 分别是ApplicationContextAwareProcessor和ApplicationListenerDetector
	 *
	 * 之后,向DefaultSingletonBeanRegistry的单例池singletonObjects中添加三个单例,分别是environment、systemProperties和systemEnvironment
	 *
	 * Configure the factory's standard context characteristics,
	 * such as the context's ClassLoader and post-processors.
	 * @param beanFactory the BeanFactory to configure
	 */
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		beanFactory.setBeanClassLoader(getClassLoader());
		if (!shouldIgnoreSpel) {
			beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		}
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (!IN_NATIVE_IMAGE && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}

		// Register default environment beans.
		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
		}

		// (Map)System.getProperties()
		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
		}

		// (Map)System.getEnv
		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
		}
	}

4 invokeBeanFactoryPostProcessors(beanFactory)

执行BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,其中BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口,所以这个方法的名字是invokeBeanFactoryPostProcessors。
这个方法主要是分别执行了用户定义的以及Spring自己的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor实现类。

/**
	 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
	 * respecting explicit order if given.
	 * <p>Must be called before singleton instantiation.
	 */
	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		/*
		* getBeanFactoryPostProcessors()获取的是当前类的属性this.beanFactoryPostProcessors,而当前类只有addBeanFactoryPostProcessor方法向beanFactoryPostProcessors增加了BeanFactoryPostProcessor,
		* 所以getBeanFactoryPostProcessors()的结果只能是用户代码显示地调用applicationContext.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor())添加的BeanFactoryPostProcessor;
		* */
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
		// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

对于AnnotationConfigApplicationContext来讲,如果用户不自己实现这BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口,那么整个方法其实最终只会调用ConfigurationClassPostProcessor的processConfigBeanDefinitions方法以及postProcessBeanFactory方法。
在Spring目前的5.2.7版本中,BeanDefinitionRegistryPostProcessor只有ConfigurationClassPostProcessor一个实现类。我们着重看一下这个类的processConfigBeanDefinitions方法(BeanDefinitionRegistryPostProcessor接口定义的方法)和postProcessBeanFactory方法(BeanFactoryPostProcessor接口定义的方法)。我们在SpringFramework源码分析(3):invokeBeanFactoryPostProcessors方法与ConfigurationClassPostProcessor详解中,会详细介绍。

  • postProcessBeanDefinitionRegistry
/**
	 * 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}

/**
	 * 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}

/**
	 * 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}

/**
	 * 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}


/**
	 * 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
	 * Derive further bean definitions from the configuration classes in the registry.
	 */
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}
  • postProcessBeanDefinitionRegistry
    postProcessBeanDefinitionRegistry方法相对简单些,主要是对@Configuration标注的类使用cglib进行增强(注意这也是一个配置类是否标注@Configuration的差异,如果不标注@Configuration则不会被cglib增强)。另外,向beanPostProcessors集合中添加了新的BeanPostProcessor,即ImportAwareBeanPostProcessor。
/**
	 * Prepare the Configuration classes for servicing bean requests at runtime
	 * by replacing them with CGLIB-enhanced subclasses.
	 */
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		int factoryId = System.identityHashCode(beanFactory);
		if (this.factoriesPostProcessed.contains(factoryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + beanFactory);
		}
		this.factoriesPostProcessed.add(factoryId);
		if (!this.registriesPostProcessed.contains(factoryId)) {
			// BeanDefinitionRegistryPostProcessor hook apparently not supported...
			// Simply call processConfigurationClasses lazily at this point then.
			processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
		}

		// 如果配置类标注了@Configuration,则将配置类对应的BeanDefinition的setClass 设置成cglib增强过的代理对象。这样在后面实例化Bean时,实例化的就是代理对象了
		enhanceConfigurationClasses(beanFactory);

		// 这里添加一个ImportAwareBeanPostProcessor的Bean实例
		beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
	}

5 registerBeanPostProcessors(beanFactory)

/**
	 * Instantiate and register all BeanPostProcessor beans, 实例化BeanPostProcessor并注册成Bean
	 * respecting explicit order if given.
	 * <p>Must be called before any instantiation of application beans.
	 */
	protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
	}

	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

		// postProcessorNames中是org.springframework.context.annotation.internalAutowiredAnnotationProcessor
		// 和org.springframework.context.annotation.internalCommonAnnotationProcessor
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

		// Register BeanPostProcessorChecker that logs an info message when
		// a bean is created during BeanPostProcessor instantiation, i.e. when
		// a bean is not eligible for getting processed by all BeanPostProcessors.
		// beanFactory.getBeanPostProcessorCount()是之前已经实例化好的BeanPostProcessor,1是BeanPostProcessorChecker,postProcessorNames是上面从BeanDefinitionMap中获取的BeanDefinition(即将被实例化成Bean)
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 通过beanFactory.getBean方法会把Bean创建出来,也就是说Spring最先创建的Bean是BeanPostProcessor
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);
				}
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, register the BeanPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

		// Next, register the BeanPostProcessors that implement Ordered.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		for (String ppName : orderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

		// Finally, re-register all internal BeanPostProcessors.
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);

		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

6 initMessageSource()

该方法比较简单,主要是为了初始化AbstractApplicationContext中的messageSource,即为messageSource赋值。具体地,如果BeanFactory中有name是messageSource的Bean,则赋值给messageSource;否则,创建一个DelegatingMessageSource赋值给messageSource。在AnnotationConfigApplicationContext中默认是创建一个DelegatingMessageSource。

7 initApplicationEventMulticaster()

该方法比较简单,主要是为了初始化AbstractApplicationContext中的applicationEventMulticaster,即为applicationEventMulticaster赋值。具体地,如果BeanFactory中有name是applicationEventMulticaster的Bean,则赋值给applicationEventMulticaster;否则,创建一个SimpleApplicationEventMulticaster赋值给applicationEventMulticaster。在AnnotationConfigApplicationContext中默认是创建一个SimpleApplicationEventMulticaster。

8 onRefresh()

初始化其他特殊的Bean,默认是空,留给AbstractApplicationContext的子类实现。

9 registerListeners()

注册Listener。比较简单,看看注释就可以了。

/**
	 * Add beans that implement ApplicationListener as listeners.
	 * Doesn't affect other listeners, which can be added without being beans.
	 */
	protected void registerListeners() {
		// Register statically specified listeners first.
		for (ApplicationListener<?> listener : getApplicationListeners()) {
			getApplicationEventMulticaster().addApplicationListener(listener);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let post-processors apply to them!
		String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
		for (String listenerBeanName : listenerBeanNames) {
			getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
		}

		// Publish early application events now that we finally have a multicaster...
		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
		this.earlyApplicationEvents = null;
		if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
				getApplicationEventMulticaster().multicastEvent(earlyEvent);
			}
		}
	}

10 finishBeanFactoryInitialization(beanFactory)

实例化所有剩余的非Lazy的Bean。因为BeanPostProcessor对应的Bean在registerBeanPostProcessors()已经变成了Bean,所以这里说的是实例化剩余的非lazy的单实例Bean。

11 finishRefresh()

主要是执行LifecycleProcessor的onRefresh方法以及发布ContextRefreshedEvent事件

4 总结

光看文章是看不太懂的,需要自己去debug。

本文地址:https://blog.csdn.net/sodawoods/article/details/107301086