Springboot启动流程

Springboot启动原理

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

我们前面讲解了启动类上的@SpringBootApplication,下面来说说SpringApplication.run(DemoApplication.class, args)这个方法做了哪些事情。这个方法是Springboot的核心

SpringApplication.run(DemoApplication.class, args)

我们进入后先来到

	public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
		return run(new Class<?>[] { primarySource }, args);
	}

然后来到

	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

可以看到大体上分为两步:

1.创建Spring容器 SpringApplication(primarySources),primarySources是我们的启动类的元数据

2.运行Spring容器 run(args),args是启动类参数(如果不传就是空,那么控制台输入的启动参数就无法生效)

创建Spring容器

创建Spring容器主要是获取一些参数,设置一些重要的属性

在执行构造方法前需要执行前面前面的一些等号来创建对象,比如set,map之类的属性值,然后来到下面的方法

	public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        //资源加载器,默认为空
		this.resourceLoader = resourceLoader;
        //判断主配置类是否为空,如果为空则报错
		Assert.notNull(primarySources, "PrimarySources must not be null");
        //设置主配置类,放入set中去重(这里的主配置类就只有一个,即启动类)
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        //判断当前web应用的类型
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //创建初始启动器,也就是项目已启动需要干的事情记录下来,类型是List<BootstrapRegistryInitializer>
		this.bootstrapRegistryInitializers = new ArrayList<>(
				getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
        //获得spring.factories中org.springframework.context.ApplicationContextInitializer配置下的所有类
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        //找到监听器,也是在spring.factories文件中找
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        //找到主启动类
		this.mainApplicationClass = deduceMainApplicationClass();
	}
1.判断web应用的类型:
	static WebApplicationType deduceFromClasspath() {
        //判断当前系统中是否存在响应式编程的处理器
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
        //因为我们这个不是响应式编程,是基于Servlet的框架,所以会返回SERVLET
		return WebApplicationType.SERVLET;
	}
2.获取初始化器
	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
        //获得类加载器
		ClassLoader classLoader = getClassLoader();
		// 获得需要在启动的时候加载的配置类(初始化引导器)
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
        //如果配置了配置了初始化引导器则生成这些引导器的示例
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
        //安装优先级排序
		AnnotationAwareOrderComparator.sort(instances);
        //返回示例(没有配置的话就默认为空)
		return instances;
	}

name是在META-INFO的spring.factories下面设置所有org.springframework.boot.BootstrapRegistryInitializer这个类型的类初始化器

其实我们见到的getSpringFactoriesInstances这个方法都是获取META-INFO目录下的spring.factories文件中的对应配置项

3.setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class))

获得spring.factories中org.springframework.context.ApplicationContextInitializer配置下的所有类,并保存在List<ApplicationContextInitializer<?>> initializers中

例如在spring-boot依赖下面就配置了一部分初始化启动器:

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

加载的时候加载了7个初始化启动器:

image-20220511120455542

可以看到这个初始化启动器确实是从spring.factories中获取到的(还有两个在其他的spring.factories中)

4.获取监听器

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

也是从spring.factories中获取要加载的监听器,类型是ApplicationListener.class

image-20220511121551982

比如我们可以看到spring-boot依赖中的spring.factories就设置了一部分ApplicationListener(这里刚好是全部)

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

和上面加载的完全匹配,说明确实是从spring.factories

5.找到主启动类

this.mainApplicationClass = deduceMainApplicationClass();

从我们刚才执行的方法中从前往后找,找到第一个含有main方法的类作为主类,也就是我们的启动类

	private Class<?> deduceMainApplicationClass() {
		try {
            //获取堆栈中的所有类和方法信息
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
            //将第一个含有main方法的类设置为主类,也就是我们的启动类
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		}
		catch (ClassNotFoundException ex) {
			// Swallow and continue
		}
		return null;
	}

image-20220511123854980

总结

创建Spring容器的过程其实就是读取配置文件,找到要加载的各个组件,配置好相关的属性,为后面的启动做好准备

运行Spring容器

前面的准备工作做好后,接下来要运行run方法:run(args)

args是我们传入的命令行参数

	public ConfigurableApplicationContext run(String... args) {
        //开始计时
		long startTime = System.nanoTime();
        //创建引导类上下文,并设置引导上下文
		DefaultBootstrapContext bootstrapContext = createBootstrapContext();
		ConfigurableApplicationContext context = null;
        //设置系统属性为headless,简单来说就是自力更生模式
		configureHeadlessProperty();
        //运行监听器
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting(bootstrapContext, this.mainApplicationClass);
		try {
            //保存命令行参数
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            //配置环境
			ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
            //设置一些需要忽略的bean
			configureIgnoreBeanInfo(environment);
            //打印banner
			Banner printedBanner = printBanner(environment);
            //创建IOC容器
			context = createApplicationContext();
            //保存项目启动这个事件
			context.setApplicationStartup(this.applicationStartup);
            //准备IOC容器
			prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
            //刷新IOC容器,创建所有的bean
			refreshContext(context);
			afterRefresh(context, applicationArguments);
            //停止计时
			Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
			if (this.logStartupInfo) {
				new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
			}
            //通知所有的监听器,容器启动
			listeners.started(context, timeTakenToStartup);
            //调用runner方法
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, listeners);
			throw new IllegalStateException(ex);
		}
		try {
			Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
			listeners.ready(context, timeTakenToReady);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
1.创建停止监视器并启动(记录启动时间)

long startTime = System.nanoTime()

2.创建引导类启动器

DefaultBootstrapContext bootstrapContext = createBootstrapContext();

	private DefaultBootstrapContext createBootstrapContext() {
		DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext();
		this.bootstrapRegistryInitializers.forEach((initializer) -> initializer.initialize(bootstrapContext));
		return bootstrapContext;
	}

创建一个Spring容器,并找到上一小节设置的初始化启动器bootstrapRegistryInitializers,逐个执行里面的initialize方法,完成一些初始化的操作

3.设置系统的状态,让当前应用进入headless模式

configureHeadlessProperty();

4.获得监听器

SpringApplicationRunListeners listeners = getRunListeners(args)

	private SpringApplicationRunListeners getRunListeners(String[] args) {
		Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
		return new SpringApplicationRunListeners(logger,
				getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
				this.applicationStartup);
	}

getSpringFactoriesInstances我们又看到了这个方法,这个方法是在META-INFO目录下spring.factories文件中找到所有SpringApplicationRunListener.class类型的类有哪些,创建这些类的对象并保存起来。

5.启动监听器

向所有的监听器发送监听信号

listeners.starting(bootstrapContext, this.mainApplicationClass);

6.保存命令行参数

ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);

7.准备运行环境

prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);

	private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
			DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
		//创建或者获取一个环境对象,会有基础的环境信息(比如环境变量和Servlet的基础信息)
		ConfigurableEnvironment environment = getOrCreateEnvironment();
        //加载各个配置源的信息
		configureEnvironment(environment, applicationArguments.getSourceArgs());
        //保存配置信息
		ConfigurationPropertySources.attach(environment);
        //通知各个监听器,当前环境准备完成
		listeners.environmentPrepared(bootstrapContext, environment);
		DefaultPropertiesPropertySource.moveToEnd(environment);
		Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
				"Environment prefix cannot be set via properties.");
        //保存配置信息
		bindToSpringApplication(environment);
		if (!this.isCustomEnvironment) {
			environment = convertEnvironment(environment);
		}
		ConfigurationPropertySources.attach(environment);
		return environment;
	}

configureEnvironment配置环境信息

	protected void configureEnvironment(ConfigurableEnvironment environment, String[] args) {
		if (this.addConversionService) {
            //设置类型转换器,完成各种数据类型的转换
			environment.setConversionService(new ApplicationConversionService());
		}
        //加载各个配置源的信息
		configurePropertySources(environment, args);
        //激活profile配置
		configureProfiles(environment, args);
	}
8.创建IOC容器

context = createApplicationContext()

根据当前应用的类型创建容器:

	protected ConfigurableApplicationContext createApplicationContext() {
		return this.applicationContextFactory.create(this.webApplicationType);
	}

因为当前的应用类型是Servlet类型,所以创建AnnotationConfigApplicationContext类型的容器

	ApplicationContextFactory DEFAULT = (webApplicationType) -> {
		try {
			for (ApplicationContextFactory candidate : SpringFactoriesLoader
					.loadFactories(ApplicationContextFactory.class, ApplicationContextFactory.class.getClassLoader())) {
				ConfigurableApplicationContext context = candidate.create(webApplicationType);
				if (context != null) {
					return context;
				}
			}
			return new AnnotationConfigApplicationContext();
		}
		catch (Exception ex) {
			throw new IllegalStateException("Unable create a default ApplicationContext instance, "
					+ "you may need a custom ApplicationContextFactory", ex);
		}
	};
9.准备IOC容器:prepareContext
	private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
			ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments, Banner printedBanner) {
        //设置基础环境信息
		context.setEnvironment(environment);
        //进行IOC容器的后置处理流程,注册一些基础组件等
		postProcessApplicationContext(context);
        //应用初始化器
		applyInitializers(context);
        //遍历所有的listener,告诉他们IOC容器初始化完成
		listeners.contextPrepared(context);
        //关闭上下文引导容器
		bootstrapContext.close(context);
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
		//拿到bean工厂
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //将applicationArguments注册为单实例bean
		beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
		if (printedBanner != null) {
            //将banner也注册为IOC容器的组件
			beanFactory.registerSingleton("springBootBanner", printedBanner);
		}
		if (beanFactory instanceof AbstractAutowireCapableBeanFactory) {
			((AbstractAutowireCapableBeanFactory) beanFactory).setAllowCircularReferences(this.allowCircularReferences);
			if (beanFactory instanceof DefaultListableBeanFactory) {
				((DefaultListableBeanFactory) beanFactory)
						.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
			}
		}
		if (this.lazyInitialization) {
			context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
		}
		// 加载资源
		Set<Object> sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		load(context, sources.toArray(new Object[0]));
        //通知所有的监听器,IOC容器加载完成
		listeners.contextLoaded(context);
	}

应用初始化器:

applyInitializers(context)

遍历所有的初始化器,调用每个初始化器的初始化方法,getInitializers()其实就是拿到获取我们在上一节我们在spring.factories中找到的所有初始化器。此时IOC容器已经初始化完成了,这个阶段是做一些额外的初始化操作,我们自定义的初始化器也会在这里生效。

	protected void applyInitializers(ConfigurableApplicationContext context) {
		for (ApplicationContextInitializer initializer : getInitializers()) {
			Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
					ApplicationContextInitializer.class);
			Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
			initializer.initialize(context);
		}
	}
10.核心代码:刷新IOC容器(创建IOC容器的所有组件)

refreshContext(context)

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			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);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

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

				// 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.
				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();
				contextRefresh.end();
			}
		}
	}
11.调用所有runner的run方法:callRunners
	private void callRunners(ApplicationContext context, ApplicationArguments args) {
		List<Object> runners = new ArrayList<>();
        //将容器中所有ApplicationRunner类的bean和CommandLineRunner类型的bean合并在一起
		runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
		runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
        //安装order注解排序
		AnnotationAwareOrderComparator.sort(runners);
        //去重后遍历所有的runner调用run方法
		for (Object runner : new LinkedHashSet<>(runners)) {
			if (runner instanceof ApplicationRunner) {
				callRunner((ApplicationRunner) runner, args);
			}
			if (runner instanceof CommandLineRunner) {
				callRunner((CommandLineRunner) runner, args);
			}
		}
	}
异常处理

如果以上步骤出现异常,会调用listerner的fail方法

12.开始监听 listeners.ready(context, timeTakenToReady)

让所有的监听器进入监听状态,如果监听出现异常则调用所有listerner的fail方法

image-20220511232423272

image-20220511232743482

image-20220511232811451

自定义监听器

applyInitializers(context) 这一步发生在准备IOC容器阶段中,此时IOC容器的基础组件都已经注册进去了

上述过程中涉及到的组件有

ApplicationContextInitializer

ApplicationListener

ApplicationRunner

CommandLineRunner

SpringApplicationRunListener

上面的组件Spring会在spring.factories定义一些,我们也可以自己定义,这些组件负责了spring容器启动的整个生命周期

ApplicationContextInitializer

ApplicationListener

SpringApplicationRunListener

定义方式:

org.springframework.context.ApplicationContextInitializer=\
  com.lun.boot.listener.MyApplicationContextInitializer

org.springframework.context.ApplicationListener=\
  com.lun.boot.listener.MyApplicationListener

org.springframework.boot.SpringApplicationRunListener=\
  com.lun.boot.listener.MySpringApplicationRunListener

这三个组件要定义在spring.factories中

ApplicationRunner

CommandLineRunner

这两类组件需要我们用@Bean,@Component注解等方式注入到Spring容器中,可以用@Order设置加载的优先级

ApplicationContextInitializer

初始化器,项目刚启动的时候执行

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("MyApplicationContextInitializer ....initialize.... ");
    }
}

ApplicationListener

监听器,上下午引导其初始化完成后执行

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class MyApplicationListener implements ApplicationListener {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("MyApplicationListener.....onApplicationEvent...");
    }
}
MyApplicationRunner

IOC容器创建结束,所有的组件注册完成后执行

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Order(1)
@Component//放入容器
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("MyApplicationRunner...run...");
    }
}

MyCommandLineRunner

IOC容器创建结束,所有的组件注册完成后执行

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * 应用启动做一个一次性事情
 */
@Order(2)
@Component//放入容器
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner....run....");
    }
}

MySpringApplicationRunListener

掌管着Spring的整个声明周期

import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    private SpringApplication application;
    public MySpringApplicationRunListener(SpringApplication application, String[] args){
        this.application = application;
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("MySpringApplicationRunListener....starting....");

    }


    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("MySpringApplicationRunListener....environmentPrepared....");
    }


    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("MySpringApplicationRunListener....contextPrepared....");

    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("MySpringApplicationRunListener....contextLoaded....");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("MySpringApplicationRunListener....started....");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("MySpringApplicationRunListener....running....");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("MySpringApplicationRunListener....failed....");
    }
}

Springboot也利用上述的声明周期来启动Tomcat,启动服务器

后续衍生技术

  • Spring Boot 2 场景整合篇
    • 虚拟化技术
    • 安全控制
    • 缓存技术
    • 消息中间件
    • 对象存储
    • 定时调度
    • 异步任务
    • 分布式系统
  • Spring Boot 2 响应式编程
    • 响应式编程基础
    • Webflux开发Web应用
    • 响应式访问持久化层
    • 响应式安全开发
    • 响应式原理

补充:IOC容器的创建流程

	@Override
	public void refresh() throws BeansException, IllegalStateException {
        //上锁
		synchronized (this.startupShutdownMonitor) {
            //通知监听器开始创建IOC容器
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			//创建容器前的预处理
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			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);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

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

				// 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.
				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();
				contextRefresh.end();
			}
		}
	}

1. 预处理前的初始化prepareRefresh()

	protected void prepareRefresh() {
		//记录时间
		this.startupDate = System.currentTimeMillis();
        //设置状态,表示激活IOC容器
		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();

		//验证一些必须的属性是否合法
		getEnvironment().validateRequiredProperties();

		//将早期事件监听器注册为监听器,并清空早期事件
		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.创建bean工厂beanFactories

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		//创建bean工厂
		refreshBeanFactory();
        //获取刚才创建的bean工厂并返回
		return getBeanFactory();
	}

创建的beanFactory的类型是DefaultListableBeanFactory,也就是默认bean工厂

3.准备bean工厂prepareBeanFactory(beanFactory)

在这个方法中,向bean工厂设置一些属性

	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
        //设置类加载器
		beanFactory.setBeanClassLoader(getClassLoader());
        //设置表达式解析器
		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 (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());
		}
		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());
		}
	}
1.设置加载bean所需的工具类
//类加载器
beanFactory.setBeanClassLoader(getClassLoader());
//表达式解析器
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//属性编辑器
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
2.设置一些回调方法
		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);

放入ApplicationContextAwareProcessor(添加部分beanPostProcessor)

忽略以这些接口创建的bean:EnvironmentAware,EmbeddedValueResolverAware,ResourceLoaderAware,ApplicationEventPublisherAware,MessageSourceAware,ApplicationContextAware

3.设置可以通过自动装配获取的bean(@Autowire,@Resource)
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

可以通过自动装配拿到BeanFactory(bean工厂),ResourceLoader(资源加载器),ApplicationEventPublisher(事件推送器),ApplicationContext(IOC容器)

4.注册ApplicationListenerDetector
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
5.添加AspectJ动态代理的支持
6.注册和环境(系统属性,环境变量)相关的组件

4.进行bean工厂创建完成后的后置处理

postProcessBeanFactory(beanFactory)

这个方法默认为空,我们重写这个方法,在beanFactory加载完成后进行一些操作

============通过以上方法完成了beanFactory的创建和预处理工作=

5.执行所有的BeanFactoryPostProcessors

invokeBeanFactoryPostProcessors

在beanFactory标准初始化完成后执行这个这个方法

两个接口:

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        
		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()));
		}
	}
1.执行所有BeanFactoryPostProcessors
1.获取所有的BeanFactoryPostProcessor
2.优先执行实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
3.然后执行实现了Order接口的BeanDefinitionRegistryPostProcessor
4.执行剩下的BeanDefinitionRegistryPostProcessor
5.获取所有的BeanFactoryPostProcessor
6.依次执行实现了PriorityOrdered,Order,没实现接口的BeanFactoryPostProcessor

6.注册bean的后置处理器

registerBeanPostProcessors(beanFactory);

也是依次注册实现了PriorityOrdered接口,实现了Order接口,没有实现任何接口的BeanFactoryPostProcessor

然后注册MergedBeanDefinitionPostProcessor和ApplicationListenerDetector

7.初始化消息(消息绑定,消息解析)

initMessageSource

如果容器中有MessageSource,则赋值给MessageSource,如果没有则自己创建一个默认的对象

MessageSource:取出某个key的值,安装区域获取值

然后将MessageSource注册进Spring容器中,然后我们就能通过自动装配得到MessageSource

8.初始化事件派发器

initApplicationEventMulticaster()

1.获取BeanFactory

2.从容器中获取applicationEventMulticaster,如果没有就创建一个SimpleApplicationEventMulticaster并注册进Spring容器

9.刷新容器onRefresh()

onRefresh()默认为空,留给我们来实现

10.注册事件派发器

获取所有的事件监听器,去重后将所有的监听器注册进事件派发器

派发之前步骤产生的事件earlyApplicationEvents

11.初始化所有所有单实例bean

finishBeanFactoryInitialization
	protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// Initialize conversion service for this context.
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		// Register a default embedded value resolver if no BeanFactoryPostProcessor
		// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
		// at this point, primarily for resolution in annotation attribute values.
		if (!beanFactory.hasEmbeddedValueResolver()) {
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}

		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// Stop using the temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(null);

		// Allow for caching all bean definition metadata, not expecting further changes.
		beanFactory.freezeConfiguration();

		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons();
	}

这个方法的核心语句是beanFactory.preInstantiateSingletons(),预加载单实例bean

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (logger.isTraceEnabled()) {
			logger.trace("Pre-instantiating singletons in " + this);
		}

        //拿到所有bean的定义信息
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						FactoryBean<?> factory = (FactoryBean<?>) bean;
						boolean isEagerInit;
						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
							isEagerInit = AccessController.doPrivileged(
									(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
									getAccessControlContext());
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}
1.preInstantiateSingletons
1.拿到扫描路径下所有带有@Controller,@Service,@Repository,@Configuration,@Component等向Spring容器中注册组件的注解的类的信息

image-20220512223534964

如上图所示,包含Spring容器中默认加载的组件和我们自己编写的

2.遍历所有的bean的全限定名,创建和初始化对应的对象
  • 拿到一个类的全限定名beanName
  • 获取这个类的定义信息RootBeanDefinition

RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName)

image-20220512232616126

  • 如果这个bean不是抽象的,也不是单实例的,也不是懒加载的
    • 然后判断是不是FactoryBean
    • 如果是FactoryBean,则使用FactoryBean的getObect方法创建bean
    • 如果不是FactoryBean,则使用getBean方法创建对象,getBean调用下面的doGetBean方法
protected <T> T doGetBean(
      String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
      throws BeansException {
   //拿到bean的名称
   String beanName = transformedBeanName(name);
   Object bean;

   //从缓存中获取单实例bean,如果能获取到说明已经被创建过了
   Object sharedInstance = getSingleton(beanName);
    //如果缓存中拿不到(不是调用了beanFactory创建bean了吗为什么拿不到,这里先伏笔一下)
   if (sharedInstance != null && args == null) {
      if (logger.isTraceEnabled()) {
         if (isSingletonCurrentlyInCreation(beanName)) {
            logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
                  "' that is not fully initialized yet - a consequence of a circular reference");
         }
         else {
            logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
         }
      }
      bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
   }

   else {
      // Fail if we're already creating this bean instance:
      // We're assumably within a circular reference.
      if (isPrototypeCurrentlyInCreation(beanName)) {
         throw new BeanCurrentlyInCreationException(beanName);
      }

      // Check if bean definition exists in this factory.
      //拿到父工厂(如果有的话)
      BeanFactory parentBeanFactory = getParentBeanFactory();
      if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
         // Not found -> check parent.
         String nameToLookup = originalBeanName(name);
         if (parentBeanFactory instanceof AbstractBeanFactory) {
            return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                  nameToLookup, requiredType, args, typeCheckOnly);
         }
         else if (args != null) {
            // Delegation to parent with explicit args.
            return (T) parentBeanFactory.getBean(nameToLookup, args);
         }
         else if (requiredType != null) {
            // No args -> delegate to standard getBean method.
            return parentBeanFactory.getBean(nameToLookup, requiredType);
         }
         else {
            return (T) parentBeanFactory.getBean(nameToLookup);
         }
      }

      if (!typeCheckOnly) {
         //标记当前bean已经被创建了,防止多个线程创建bean
         markBeanAsCreated(beanName);
      }

      try {
         //获取bean的定义信息
         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
         checkMergedBeanDefinition(mbd, beanName, args);

         // Guarantee initialization of beans that the current bean depends on.
          //获取当前bean依赖的其他bean
         String[] dependsOn = mbd.getDependsOn();
         if (dependsOn != null) {
            //如果当前有依赖的bean,则遍历所有依赖的bean,创建所有依赖的bean
            for (String dep : dependsOn) {
               if (isDependent(beanName, dep)) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
               }
               registerDependentBean(dep, beanName);
               try {
                  //尝试获取或者创建所依赖的bean(这里发生了递归)
                  getBean(dep);
               }
               catch (NoSuchBeanDefinitionException ex) {
                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
               }
            }
         }

         // Create bean instance.
         //如果这是一个单实例bean,则采用单实例bean的创建方法
         if (mbd.isSingleton()) {
            //调用getSingleton方法(上面也调用这个方法)创建或者从一二级缓存中获取bean,这里的lamda表达式省略的是beanFactory的getObject方法
            sharedInstance = getSingleton(beanName, () -> {
               try {
                   //调用createBean方法创建bean
                  return createBean(beanName, mbd, args);
               }
               catch (BeansException ex) {
                  // Explicitly remove instance from singleton cache: It might have been put there
                  // eagerly by the creation process, to allow for circular reference resolution.
                  // Also remove any beans that received a temporary reference to the bean.
                  destroySingleton(beanName);
                  throw ex;
               }
            });
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
         }

         else if (mbd.isPrototype()) {
            // It's a prototype -> create a new instance.
            Object prototypeInstance = null;
            try {
               beforePrototypeCreation(beanName);
               prototypeInstance = createBean(beanName, mbd, args);
            }
            finally {
               afterPrototypeCreation(beanName);
            }
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
         }

         else {
            String scopeName = mbd.getScope();
            if (!StringUtils.hasLength(scopeName)) {
               throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
            }
            Scope scope = this.scopes.get(scopeName);
            if (scope == null) {
               throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
            }
            try {
               Object scopedInstance = scope.get(beanName, () -> {
                  beforePrototypeCreation(beanName);
                  try {
                     return createBean(beanName, mbd, args);
                  }
                  finally {
                     afterPrototypeCreation(beanName);
                  }
               });
               bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
            }
            catch (IllegalStateException ex) {
               throw new BeanCreationException(beanName,
                     "Scope '" + scopeName + "' is not active for the current thread; consider " +
                     "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                     ex);
            }
         }
      }
      catch (BeansException ex) {
         cleanupAfterBeanCreationFailure(beanName);
         throw ex;
      }
   }

   // Check if required type matches the type of the actual bean instance.
   if (requiredType != null && !requiredType.isInstance(bean)) {
      try {
         T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
         if (convertedBean == null) {
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
         }
         return convertedBean;
      }
      catch (TypeMismatchException ex) {
         if (logger.isTraceEnabled()) {
            logger.trace("Failed to convert bean '" + name + "' to required type '" +
                  ClassUtils.getQualifiedName(requiredType) + "'", ex);
         }
         throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      }
   }
   return (T) bean;
}

核心方法doGetBean

1.从缓存中获取单实例bean,如果能获取到说明已经被创建过了

Object sharedInstance = getSingleton(beanName)

(单例设计模式)

	@Nullable
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		//尝试从一级缓存中拿到bean
		Object singletonObject = this.singletonObjects.get(beanName);
        //如果没有拿到
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            //再尝试从二级缓存中找
			singletonObject = this.earlySingletonObjects.get(beanName);
            //如果二级缓存中也没有找到,并且允许提前创建bean
			if (singletonObject == null && allowEarlyReference) {
                //锁住一级缓存(单例模式)
				synchronized (this.singletonObjects) {
					//再尝试从一级缓存中找
					singletonObject = this.singletonObjects.get(beanName);
                    //如果一级缓存中没有找到
					if (singletonObject == null) {
                        //从二级缓存中找
						singletonObject = this.earlySingletonObjects.get(beanName);
                        //如果二级缓存中没有找到
						if (singletonObject == null) {
                            //从三级中找到对应的beanFactory,准备执行创建的bean的流程
							ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                            //如果找到了beanFactory
							if (singletonFactory != null) {
                                //使用beanFactory创建bean
								singletonObject = singletonFactory.getObject();
                                //将这个bean放入二级缓存
								this.earlySingletonObjects.put(beanName, singletonObject);
                                //从三级缓存中移除beanFactory
								this.singletonFactories.remove(beanName);
							}
						}
					}
				}
			}
		}
		return singletonObject;
	}

singletonObjects:一级缓存:单例池

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

其实就是一个线程安全的map的

earlySingletonObjects:二级缓存,用于保存半成品的bean

private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

同样是一个线程安全的map

singletonFactories:三级缓存,用于保存bean工厂

private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

同样是一个线程安全的map,但是保存的是 ObjectFactory<?>

核心方法createBean

	@Override
	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		if (logger.isTraceEnabled()) {
			logger.trace("Creating instance of bean '" + beanName + "'");
		}
		RootBeanDefinition mbdToUse = mbd;

		// Make sure bean class is actually resolved at this point, and
		// clone the bean definition in case of a dynamically resolved Class
		// which cannot be stored in the shared merged bean definition.
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}

		// Prepare method overrides.
		try {
			mbdToUse.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            //给这个bean一个返回代理对象的机会
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
            //如果没有返回代理对象,则创建bean
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
			// A previously detected exception with proper bean creation context already,
			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
	}

创建bean:doCreateBean

	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
            //创建bean实例
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
			mbd.resolvedTargetType = beanType;
		}

		// Allow post-processors to modify the merged bean definition.
        //加上锁,防止多次后置处理,确保只处理一次
		synchronized (mbd.postProcessingLock) {
            //如果没有被后置处理
			if (!mbd.postProcessed) {
				try {
                    //执行一些后置处理器
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
                //标志位已经被后置处理
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
        //第二级缓存能处理循环依赖,及时有了生命周期的处理方法
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isTraceEnabled()) {
				logger.trace("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
            //为bean赋值
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
            //获取早期保留的bean的引用
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
            //注册bean的销毁
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}
		//返回创建好的bean
		return exposedObject;
	}

创建对象实例 createBeanInstance

	protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
		// Make sure bean class is actually resolved at this point.
        //获取当前的bean是什么类型
		Class<?> beanClass = resolveBeanClass(mbd, beanName);

		if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
		}

		Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
        //如果是实例bean(@Component)
		if (instanceSupplier != null) {
			return obtainFromSupplier(instanceSupplier, beanName);
		}
		//如果是用@bean注解创建
		if (mbd.getFactoryMethodName() != null) {
            //利用对象的构造器创建bean实例
			return instantiateUsingFactoryMethod(beanName, mbd, args);
		}

		// Shortcut when re-creating the same bean...
		boolean resolved = false;
		boolean autowireNecessary = false;
		if (args == null) {
			synchronized (mbd.constructorArgumentLock) {
				if (mbd.resolvedConstructorOrFactoryMethod != null) {
					resolved = true;
					autowireNecessary = mbd.constructorArgumentsResolved;
				}
			}
		}
		if (resolved) {
			if (autowireNecessary) {
				return autowireConstructor(beanName, mbd, null, null);
			}
			else {
				return instantiateBean(beanName, mbd);
			}
		}

		// Candidate constructors for autowiring?
		Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}

属性赋值populateBean

image-20220513101910052

12.完成beanFactory的创建工作

	protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
        //初始化
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}
1.初始化LifecycleProcessor(需要我们来实现)
2.执行getLifecycleProcessor().onRefresh();
3.发布容器创建完成事件

publishEvent(new ContextRefreshedEvent(this))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值