第一节 参考

一.参考


<从零开始写javaweb框架>
<Spring源码深度解析>
https://blog.csdn.net/u010723709/article/details/47185959
https://blog.csdn.net/array_dear/article/details/87399976

spring源码apply plugin: “kotlin“报错_apply plugin: 'kotlin-CSDN博客


二.编译

5.x的代码在windows平台编译涉及到kotlin,各种报错,放弃了,改用4.3的源码分析.
https://github.com/spring-projects/spring-framework下载源码
按照gradle,进入对应模块,执行gradle clean build -x test.
注意看import-into-idea.md文件.先执行gradlew :spring-oxm:compileTestJava.再执行gradlew idea -x test.

如果遇到compileKotlin找不到classpath,可以删除spring-beas.gradle的classpaht += xxx这一行.

build.gradle里面修改仓库为aliyun地址,修改kotalin版本为idea中的kotlin插件的版本.

jdk.jfr.Category类找不到时,设置gradle的jdk版本为jdk11.


第二节 架构

一.主要模块


核心为IoC依赖注入和AOP面向切面的功能,在此基础上,实现了webmvc,spring-tx事务,spring-jdbc数据库连接,spring-jms消息,spring-expression表达式解析等功能.
1.spring-core
包含IoC的部分功能,io操作,序列化,util,cglib等的一些工具包.
2.spring-beans
主要实现IOC功能,包含BeansFactory,单例,注解支持,bean的xml解析等.
3.spring-context
主要实现spring的容器加载,容器扩展功能,核心为ApplicationContext接口.支持spring容器通过xml或者扫描注解加载,国际化,事务传播等。也支持通过第三方模块的调用,比如缓存,邮件,调度,模板引擎等.
4.spring-expression
主要实现对容器中bean对象的检索功能
5.spring-jdbc
提供对数据库,jdbc的方便调用
6.spring-orm
提供对jpa,hibernate的集成调用.
7.spring-oxm
提供object对象和xml文件的转换功能
8.spring-jms
提供生产者和消费者的异步消息模型的调用.
9.spring-tx
支持编程式和声明式事务管理功能.
10.spring-web
实现spring的http协议解析功能,比如http的header和body的解析,编解码,序列化,文件上传.
11.spring-webmvc
实现spring的servlet功能.核心类为DispatcherServlet.包含web请求的解析,返回视图解析等.
12.spring-websocket
支持websocket功能
13.spring-aop
面向切面AOP的功能
14.spring-aspects
集成AspectJ框架,实现aspect注解功能.


第三节 源码细节

一.Refresh入口


1.IOC核心是AbstractApplicationContext.refresh()方法.

2.测试用例入口GenericXmlApplicationContextTests.classRelativeResourceLoading_load()方法.

3.普通的spring mvc的工程入口是spring-webmvc模块的FrameworkServlet.initServletBean()方法创建WebApplicationContext,即XmlWebApplicationContext,调用WebApplicationContext.refresh()方法.

4.以2.4.7版本的springboot为例,依赖5.3.8版本的spring,入口是org.springframework.boot.SpringApplication#run()->org.springframework.boot.SpringApplication#refreshContext->org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#refresh->org.springframework.context.support.AbstractApplicationContext#refresh

refresh()方法代码如下:

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		/* 
        见下面2处
		 加载spring的xml文件.
		 1.在AbstractXmlApplicationContext#loadBeanDefinitions()方法中调用getDefaultConfigLocations()找到spring的xml文件路径.
		 2.调用AbstractBeanDefinitionReader.loadBeanDefinitions()->XmlBeanDefinitionReader#loadBeanDefinitions()调用jax库加载xml文件,
         解析成Document格式.注册到DefaultListableBeanFactory#beanDefinitionMap中.
		 3.创建一个DefaultListableBeanFactory对象返回.
		 */
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		//见下面3处
        //注册一些BeanPostProcessor,比如ApplicationContextAwareProcessor.
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			/* 
            见下面4处.
            注册一些xml文件中配置的BeanFactoryPostProcessor.BeanDefinitionRegistryPostProcessor是对前者的补充继承.
            比如ConfigurationClassPostProcessor(对注解bean的处理),PropertyPlaceholderConfigurer.注册完后直接调用invokeBeanDefinitionRegistryPostProcessors()方法
            回调每一个BeanFactoryPostProcessor实现类的postProcessBeanDefinitionRegistry()方法。比如调用ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()
            实现对注解bean的注册.这里也处理springboot启动类的@ComponentScan注解,扫描它的basePackage,加载所有bean定义.见下面5处.
			在invokeBeanFactoryPostProcessors()方法中继续调用invokeBeanFactoryPostProcessors,回调BeanFactoryPostProcessor类的postProcessBeanFactory()方法.比如
            ConfigurationClassPostProcessor.postProcessBeanFactory()方法.在这个方法中添加ImportAwareBeanPostProcessor. 
			BeanFactoryPostProcessor在这里调用执行,BeanPostProcessor在bean创建时执行,这里就是区别
			*/
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			/* 注册xml文件中配置的BeanPostProcessor.注册BeanPostProcessor,在后面调用getBean()方法,bean实例化时回调postProcessBeforeInitialization()和postProcessAfterInitialization.
			BeanPostProcessor类的实例,比如AutowiredAnnotationBeanPostProcessor(处理autowire注解),RequiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor
            (处理Resource注解). */
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			//默认添加DelegatingMessageSource()处理语言的国际化.国际化后面新开贴分析。
			initMessageSource();

			// Initialize event multicaster for this context.
			//默认添加SimpleApplicationEventMulticaster类作为事件广播器.事件广播器后面新开贴介绍.
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			//默认是空实现,交给子类处理
			onRefresh();

			// Check for listener beans and register them.
			//注册实现了ApplicationListener接口的类到AbstractApplicationEventMulticaster#defaultRetriever里面,默认是空的
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			/* 
			对于非延迟加载的bean,实例化对象并初始化成员.进入DefaultListableBeanFactory.preInstantiateSingletons(),调用getBean,初始化bean.
            比如xxxController,xxxService,aop代理类,internalConfigurationAnnotationProcessor,internalAutowiredAnnotationProcessor,internalRequiredAnnotationProcessor,
            internalCommonAnnotationProcessor,internalEventListenerProcessor,propertyConfigurer等
			*/
			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();
		}
	}
}


二.obtainFreshBeanFactory()

xml中bean的注册.加载xml,注册bean.
核心处理是进入XmlBeanDefinitionReader.doLoadBeanDefinitions()

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
	try {
		//调用jax库加载xml为Document格式
		Document doc = doLoadDocument(inputSource, resource);
		//创建DefaultBeanDefinitionDocumentReader
		//进入DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions()->DefaultBeanDefinitionDocument//Reader#parseBeanDefinitions()->DefaultBeanDefinitionDocumentReader#parseDefaultElement解析标签,把Document解析到类型为BeanDefinitionParserDelegate的DefaultBeanDefinitionDocumentReader#delegate里面.
		//返回已经注册的bean的个数,这里为0
		return registerBeanDefinitions(doc, resource);
	}
	...
}

解析标签

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
	if (delegate.isDefaultNamespace(root)) {
		NodeList nl = root.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (node instanceof Element) {
				Element ele = (Element) node;
				if (delegate.isDefaultNamespace(ele)) {
					//解析默认的四个标签,即import,bean,beans,alias
					parseDefaultElement(ele, delegate);
				}
				else {
					//解析自定义标签,比如context:component,annotation-config
					//先进入BeanDefinitionParserDelegate#parseCustomElement(),调用ContextNamespaceHandler#init()注册常用几个标签的处理类.然后调用处理类的NamespaceHandler#parse()方法解析标签
					delegate.parseCustomElement(ele);
				}
			}
		}
	}
	else {
		delegate.parseCustomElement(root);
	}
}

自定义标签处理逻辑BeanDefinitionParserDelegate#parseCustomElement()
 

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
	//获取标签的命名空间
	String namespaceUri = getNamespaceURI(ele);
	//调用下面的ContextNamespaceHandler.init()方法注册标签处理类
	NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
	if (handler == null) {
		error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
		return null;
	}
	//调用标签的解析方法
	return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

注册自定义标签解析类ContextNamespaceHandler.init(),所谓注册就是放到beanDefinitionMap,beanDefinitionNames中.默认下面一共注册了六个.

public void init() {
	//用来处理配置文件中的占位符
	registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
	registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
	/* 
	注册第一个ConfigurationClassPostProcessor(实现了BeanFactoryPostProcessor接口),第二个AutowiredAnnotationBeanPostProcessor,
	第三个RequiredAnnotationBeanPostProcessor,第四个CommonAnnotationBeanPostProcessor(这几个都实现了BeanPostProcessor接口),第五个EventListenerMethodProcessor(实现了ApplicationContextAware接口),第六个DefaultEventListenerFactory
	*/
	registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
	//扫描目录,标记有@Component注解,@Service,@Controller,@Repository都有这个注解
	registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
	registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
	registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
	registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
	registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
}

标签解析DefaultBeanDefinitionDocumentReader#parseDefaultElement
 

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
	//解析import标签
	if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
		importBeanDefinitionResource(ele);
	}
	//解析alias标签
	else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
		processAliasRegistration(ele);
	}
	//解析bean标签
	else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
		processBeanDefinition(ele, delegate);
	}
	//解析beans标签
	else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
		// recurse
		doRegisterBeanDefinitions(ele);
	}
}

解析Bean标签

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	//解析bean标签的id,name等属性值到BeanDefinitionHolder的成员变量里面
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			//进入DefaultListableBeanFactory#registerBeanDefinition()方法.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}

注册标签。注册到DefaultListableBeanFactory

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

	...
	BeanDefinition oldBeanDefinition;

	oldBeanDefinition = this.beanDefinitionMap.get(beanName);
	//已经注册过的bean,抛异常或者覆盖
	if (oldBeanDefinition != null) {
		if (!isAllowBeanDefinitionOverriding()) {
			throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
					"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
					"': There is already [" + oldBeanDefinition + "] bound.");
		}
		...
		this.beanDefinitionMap.put(beanName, beanDefinition);
	}
	else {
		//如果已经创建过bean
		if (hasBeanCreationStarted()) {
			// Cannot modify startup-time collection elements anymore (for stable iteration)
			synchronized (this.beanDefinitionMap) {
				this.beanDefinitionMap.put(beanName, beanDefinition);
				List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1);
				updatedDefinitions.addAll(this.beanDefinitionNames);
				updatedDefinitions.add(beanName);
				this.beanDefinitionNames = updatedDefinitions;
				if (this.manualSingletonNames.contains(beanName)) {
					Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames);
					updatedSingletons.remove(beanName);
					this.manualSingletonNames = updatedSingletons;
				}
			}
		}
		else {
			//向beanDefinitionMap,beanDefinitionNames中注册bean
			// Still in startup registration phase
			this.beanDefinitionMap.put(beanName, beanDefinition);
			this.beanDefinitionNames.add(beanName);
			this.manualSingletonNames.remove(beanName);
		}
		this.frozenBeanDefinitionNames = null;
	}

	if (oldBeanDefinition != null || containsSingleton(beanName)) {
		resetBeanDefinition(beanName);
	}
}

三.prepareBeanFactory()

准备bean工厂的一些参数.bean工厂即DefaultListableBeanFactory


 

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	//设置bean工厂的类加载器,默认是AppClassLoader.
	beanFactory.setBeanClassLoader(getClassLoader());
	//设置bean标签的 表达式的解析器
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	//设置资源文件的注册
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	//重要,添加各种xxxAware接口的观察者
	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的依赖?干啥用的
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (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.
	//向singletonObjects直接添加系统默认的三个bean,读取配置文件的systemProperties,systemEnvironment,environment
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

四.invokeBeanFactoryPostProcessors

默认传进来的beanFactoryPostProcessors是空的。springboot是有三个CachingMetadataReaderFactoryPostProcessor,ConfigurationWarningsPostProcessor,PropertySourceOrderingPostProcessor.

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	// Invoke BeanDefinitionRegistryPostProcessors first, if any.
	Set<String> processedBeans = new HashSet<String>();

	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
		List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
				new LinkedList<BeanDefinitionRegistryPostProcessor>();

		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryPostProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
				registryPostProcessors.add(registryPostProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// Separate between BeanDefinitionRegistryPostProcessors that implement
		// PriorityOrdered, Ordered, and the rest.
		/* 从beanDefinitionMap中取出实现了BeanFactoryPostProcessor接口的对象,下面代码直接去调用
		默认是空。如果配置了<context:annotation-config/>.<context:component-scan/>,这里是ConfigurationClassPostProcessor
		*/
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

	    //调用实现了BeanDefinitionRegistryPostProcessors接口的类,按照顺序,先调用PriorityOrdered,再调用Ordered,
	    //最后调用剩下的
		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
		//对几个BeanFactoryPostProcessor接口实现类排个序
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
		registryPostProcessors.addAll(priorityOrderedPostProcessors);
		/*
		调用ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(),在这里面注册ImportAwareBeanPostProcessor处理import注
        解(比如aop的注解实现@Import(AspectJAutoProxyRegistrar.class)),EnhancedConfigurationBeanPostProcessor
		*/
		invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
		for (String ppName : postProcessorNames) {
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(beanFactory, orderedPostProcessors);
		registryPostProcessors.addAll(orderedPostProcessors);
		//在前面的invokeBeanDefinitionRegistryPostProcessors可能新增了实现类,这里再调用一次.
		//在上面的循环中已经排除了processedBeans里面已经调用过得实现类,不会重复调用
        //这里处理springboot的@ComponentScan注解,扫描包,加入bean定义.默认只有一个ConfigurationClassPostProcessor,见下面5处.
		invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
					BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
					registryPostProcessors.add(pp);
					processedBeans.add(ppName);
					pp.postProcessBeanDefinitionRegistry(registry);
					reiterate = true;
				}
			}
		}

		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// Invoke factory processors registered with the context instance.
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let the bean factory post-processors apply to them!
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	//调用实现了BeanFactoryPostProcessors接口的类,按照顺序,先调用PriorityOrdered,再调用Ordered,
	//最后调用剩下的
	// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	List<String> orderedPostProcessorNames = new ArrayList<String>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(beanFactory, orderedPostProcessors);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// Clear cached merged bean definitions since the post-processors might have
	// modified the original metadata, e.g. replacing placeholders in values...
	beanFactory.clearMetadataCache();
}

五.注解类bean的注册

栈调用如下图所示:

1.由上面的四处进来.依次进入AbstractApplicationContext#invokeBeanFactoryPostProcessors->PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()->PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors->ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry->ConfigurationClassPostProcessor#processConfigBeanDefinitions(扫描到所有带有@Configuration注解的类)->ComponentScanAnnotationParser#parse(解析ComponentScan注解中配置的basePackages目录,扫描该目录,获取所有的注解bean)

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        //扫描所有beanFactoryPostProcessor
		String[] candidateNames = registry.getBeanDefinitionNames();

        //遍历所有beanFactoryPostProcessor,过滤出带有@Configuration注解的类
		for (String beanName : candidateNames) {
			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);
				}
			}
			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;
		}
        //xxx
		// 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 {
			StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
            //解析出来所有的@ComponentScan下的定义的bean
            //进入ConfigurationClassParser#doProcessConfigurationClass.见下面2处.
			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());
			}
            //加载所有的@ComponentScan定义的bean中实现了ImportBeanDefinitionRegistrar接口或者import的类到beanDefinnationMap中
			this.reader.loadBeanDefinitions(configClasses);
			alreadyParsed.addAll(configClasses);
			processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

			candidates.clear();
			//xxx
		}
		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());
		}
		//xxx
	}

2.进入ConfigurationClassParser#doProcessConfigurationClass,代码如下

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
		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
		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
		if (!componentScans.isEmpty() &&
				!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
			for (AnnotationAttributes componentScan : componentScans) {
				// The config class is annotated with @ComponentScan -> perform the scan immediately
                //扫描出所有的@ComponentScan包路径下的bean定义
				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
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
					if (bdCand == null) {
						bdCand = holder.getBeanDefinition();
					}
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
						parse(bdCand.getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// Process any @Import annotations
        //处理带有@Import注解的类.主要是处理@ImportSelector注解,调用实现类的ImportSelector#selectImports方法,批量导入bean定义.
		processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

		// Process any @ImportResource annotations
		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注解的类
		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;
	}

3.进入ClassPathBeanDefinitionScanner#doScan扫描@ComponentScan的包路径.

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
		Assert.notEmpty(basePackages, "At least one base package must be specified");
		Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
		for (String basePackage : basePackages) {
            //读取包下的类文件,过滤出所有带有@Component注解的类.service,controller等都有component注解.这里都会扫描出来.
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				if (candidate instanceof AnnotatedBeanDefinition) {
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
                //检查bean,创建BeanDefinitionHolder对象
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
                    //进入DefaultListableBeanFactory#registerBeanDefinition方法,放到beanDefinition容器中.
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

进入DefaultListableBeanFactory#registerBeanDefinition,放入DefaultListableBeanFactory#beanDefinitionMap和DefaultListableBeanFactory#beanDefinitionNames中.

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()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				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()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				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 {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
		else if (isConfigurationFrozen()) {
			clearByTypeCache();
		}
	}

六.registerBeanPostProcessors()

注册BeanPostProcessor到类型为List<BeanPostProcessor>的AbstractBeanFactory#beanPostProcessors成员中,在后面bean实例化时回调postProcessBeforeInitialization()和postProcessAfterInitialization。前面是处理BeanFactoryPostProcessor,这里是BeanPostProcessor,注意区分。需要自己实现BeanPostProcessor方法.

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

	/* 获取beanDefinitionMap中实现了BeanPostProcessor接口的实现类
	这里有EnhancedConfigurationBeanPostProcessor,ImportAwareBeanPostProcessor,CommonAnnotationBeanPostProcessor,
	RequiredAnnotationBeanPostProcessor,AutowiredAnnotationBeanPostProcessor五个,都是在前面注册过的.
	*/
	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.
	//添加对BeanPostProcessor的检查类,也做日志记录
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	//对实现了PriorityOrdered接口的BeanPostProcessor类,单独存储,优先处理.
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
	List<String> orderedPostProcessorNames = new ArrayList<String>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			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(beanFactory, priorityOrderedPostProcessors);
	//所谓注册就是,之前只是把这些实现类放到beanDefinitionMap中,现在放到AbstractBeanFactory#beanPostProcessors中,后面调用时//从这个成员里面取
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

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

	// Now, register all regular BeanPostProcessors.
	//注册不是PriorityOrdered优先的BeanPostProcessor实现类,放到AbstractBeanFactory#beanPostProcessors中.
	//这里默认为空列表
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
	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(beanFactory, internalPostProcessors);
	registerBeanPostProcessors(beanFactory, internalPostProcessors);

	//添加ApplicationListenerDetector作为BeanPostProcessor,做什么用?
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

七.finishBeanFactoryInitialization()

实例化bean对象并初始化成员.
进入DefaultListableBeanFactory#preInstantiateSingletons()方法处理.
里面的getBean()新开贴分析.

public void preInstantiateSingletons() throws BeansException {
	// Iterate over a copy to allow for init methods which in turn register new bean definitions.
	// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
	//取出所有注册过的bean
	List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

	// Trigger initialization of all non-lazy singleton beans...
	/* 遍历所有的bean,一个个调用getBean()实例化和初始化成员
	这里除了业务bean,加了context:component,annotation-config注解的话,spring自带有八个bean
	*/
	for (String beanName : beanNames) {
		//这里是如果通过beanName找不到AbstractBeanFactory#mergedBeanDefinitions中的bean定义,通过父子关系查找,后面新开贴分析
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		//如果bean不是抽象类,是单例的类,不是延迟加载的就开始创建过程
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			//如果是FactoryBean,需要处理getObjectType(),getObject()
			if (isFactoryBean(beanName)) {
				final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
				boolean isEagerInit;
				if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
					isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
						@Override
						public Boolean run() {
							return ((SmartFactoryBean<?>) factory).isEagerInit();
						}
					}, getAccessControlContext());
				}
				else {
					isEagerInit = (factory instanceof SmartFactoryBean &&
							((SmartFactoryBean<?>) factory).isEagerInit());
				}
				if (isEagerInit) {
					getBean(beanName);
				}
			}
			else {
				//不是工厂bean,直接开始创建过程
				getBean(beanName);
			}
		}
	}

	// Trigger post-initialization callback for all applicable beans...
	for (String beanName : beanNames) {
		//从singletonObjects获取所有创建的bean对象
		Object singletonInstance = getSingleton(beanName);
		//如果bean对象实现了SmartInitializingSingleton接口,调用它的afterSingletonsInstantiated()方法
		//EventListenerMethodProcessor实现了这个接口
		if (singletonInstance instanceof SmartInitializingSingleton) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged(new PrivilegedAction<Object>() {
					@Override
					public Object run() {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}


 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐