专栏首页技术进阶之路Spring 容器的创建过程

Spring 容器的创建过程

文章目录
  • 概览
  • 1、prepareRefresh
    • 1.1、initPropertySources
    • 1.2、validateRequiredProperties
  • 2、obtainFreshBeanFactory
    • 2.1、refreshBeanFactory
    • 2.2、getBeanFactory
  • 3、prepareBeanFactory
  • 4、postProcessBeanFactory
  • 5、invokeBeanFactoryPostProcessors
    • 5.0、invokeBeanFactoryPostProcessors
  • 6、registerBeanPostProcessors
    • 6.0、registerBeanPostProcessors
  • 7、initMessageSource
  • 8、initApplicationEventMulticaster
  • 9、onRefresh
  • 10、registerListeners
  • 11、finishBeanFactoryInitialization
    • 11.0、preInstantiateSingletons
      • resolveBeforeInstantiation
      • doCreateBean
  • 12、finishRefresh

概览

首先写一个测试类,我们使用纯注解的方式看一下 Spring 容器的加载过程:

@Test
public void test() {
    ApplicationContext context = new AnnotationConfigApplicationContext(ExtractConfig.class);
}

然后 debug 分析。

Spring 容器首先会执行 org.springframework.context.annotation.AnnotationConfigApplicationContext 的一个方法:

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
	this();
	register(annotatedClasses);
	refresh();
}
该类父类的位置:
org.springframework.context.support.AbstractApplicationContext

主要是 AbstractApplicationContextrefresh 方法,Spring 通过该方法创建并初始化所有的 Bean。

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
	
		// 准备容器的刷新
		1.prepareRefresh();
		
		// 告诉子类去创建内置的 beanFactory.
		2.ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		
		// bean factory 的预准备工作
		3.prepareBeanFactory(beanFactory);
		
		try {
			// Allows post-processing of the bean factory in context subclasses.
			4.postProcessBeanFactory(beanFactory);
			// Invoke factory processors registered as beans in the context.
			5.invokeBeanFactoryPostProcessors(beanFactory);
			// Register bean processors that intercept bean creation.
			6.registerBeanPostProcessors(beanFactory);
			// Initialize message source for this context.
			7.initMessageSource();
			// Initialize event multicaster for this context.
			8.initApplicationEventMulticaster();
			// Initialize other special beans in specific context subclasses.
			9.onRefresh();
			// Check for listener beans and register them.
			10.registerListeners();
			// Instantiate all remaining (non-lazy-init) singletons.
			11、finishBeanFactoryInitialization(beanFactory);
			// Last step: publish corresponding event.
			12、finishRefresh();
		}
		catch (BeansException ex) {
			。。。
			throw ex;
		}
		finally {
			。。。
			resetCommonCaches();
		}
	}
}

可以看到采用了线程安全的锁机制,然后执行一系列的操作,我按照顺序分为了 12 个步骤,下面一个一个的看一下每个方法的作用。

1、prepareRefresh

首先是 org.springframework.context.support.AbstractApplicationContext # prepareRefresh 方法 ,它执行的是刷新前的预处理工作。

protected void prepareRefresh() {
	this.startupDate = System.currentTimeMillis();
	this.closed.set(false);
	this.active.set(true);
	if (logger.isDebugEnabled()) {
		if (logger.isTraceEnabled()) {
			logger.trace("Refreshing " + this);
		}
		else {
			logger.debug("Refreshing " + getDisplayName());
		}
	}
	// 初始化一些属性设置
	1.initPropertySources();
	// 校验属性 检验属性是否合法
	2.getEnvironment().validateRequiredProperties();
	
	// 用于保存容器中一些早期的事件
	this.earlyApplicationEvents = new LinkedHashSet<>();
}

1.1、initPropertySources

点进去该方法显示是空的:

protected void initPropertySources() {
	// For subclasses: do nothing by default.
}

这里是留给子类自定义属性设置方法。

1.2、validateRequiredProperties

主要是 org.springframework.core.env.AbstractPropertyResolver # validateRequiredProperties 方法,内容如下:

@Override
public void validateRequiredProperties() {
	MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
	for (String key : this.requiredProperties) {
		if (this.getProperty(key) == null) {
			ex.addMissingRequiredProperty(key);
		}
	}
	if (!ex.getMissingRequiredProperties().isEmpty()) {
		throw ex;
	}
}

2、obtainFreshBeanFactory

方法内容如下:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	1.refreshBeanFactory();
	return 2.getBeanFactory();
}

2.1、refreshBeanFactory

来到了 org.springframework.context.support.GenericApplicationContext # refreshBeanFactory 方法,首先调用 GenericApplicationContext 的构造方法创建了一个 new DefaultListableBeanFactory() ,然后在这里给它序列化了一下,设置了 ID

@Override
protected final void refreshBeanFactory() throws IllegalStateException {
	if (!this.refreshed.compareAndSet(false, true)) {
		throw new IllegalStateException(
				"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
	}
	this.beanFactory.setSerializationId(getId());
}

2.2、getBeanFactory

来到了 org.springframework.context.support.GenericApplicationContext # getBeanFactory 方法,就是返回了刚才创建的 beanFactory

@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
	return this.beanFactory;
}

到此为止 BeanFactory 对象已经有了,他是 DefaultListableBeanFactory 类型的。

3、prepareBeanFactory

该方法主要是对 BeanFactory 进行一些基本的设置,比如类加载器、表达式解析器、添加部分的 BeanPostProcessorApplicationContextAwareProcessor、设置忽略的自动装配的接口。

然后注册可以解析的自动装配,这些组件以后可以直接注入。

最后给 BeanFactory 注册一些能用的组件:

  1. 设置环境:ConfigurableEnvironment
  2. 设置系统属性值:Map<String, Object>
  3. 设置系统环境:Map<String, Object>
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());
	}
}

4、postProcessBeanFactory

该方法进行 BeanFactory 准备工作完成后的后置处理工作。

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

这里也是空的,说明子类可以重写该方法进一步设置 BeanFactory

以上是 BeanFactory 的创建及预准备工作。


5、invokeBeanFactoryPostProcessors

执行 BeanFactory 的后置处理器,是在工厂准备标准初始化完成之后进行的。

这里涉及两个接口,分别是:BeanFactoryPostProcessorBeanDefinitionRegistryPostProcessor

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	1、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()));
	}
}

从容器中找到所有的 PostProcessor

public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
	return this.beanFactoryPostProcessors;
}

5.0、invokeBeanFactoryPostProcessors

到了 org.springframework.context.support.PostProcessorRegistrationDelegate # invokeBeanFactoryPostProcessors 方法。

该方法很长,所以不提供代码了:

  1. 首先获取所有的 BeanDefinitionRegistryPostProcessor
  2. 根据优先级规则排序并执行每个 BeanDefinitionRegistry 后置处理器。
  3. 然后获取所有的 BeanFactoryPostProcessor
  4. 根据优先级规则排序并执行每个 BeanFactory 后置处理器

BeanDefinitionRegistryPostProcessor 为例,查看源码简单过一下流程。

// 获取
String[] postProcessorNames =
		beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
	if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
		currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
		processedBeans.add(ppName);
	}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();

6、registerBeanPostProcessors

这一步是注册 Bean 的后置处理器,作用是拦截 Bean 的创建过程。

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

来到了 org.springframework.context.support.PostProcessorRegistrationDelegate # registerBeanPostProcessors 方法。

6.0、registerBeanPostProcessors

不同类型的 BeanPostProcessor ,在 Bean 创建前后的执行时机是不一样的。

  • MergedBeanDefinitionPostProcessor
  • DestructionAwareBeanPostProcessor
  • InstantiationAwareBeanPostProcessor
  • SmartInstantiationAwareBeanPostProcessor

也是首先获取所有的后置处理器。

String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

按照 PriorityOrderedOrdered 进行优先级排序。

按照顺序分别注册实现优先级接口的后置处理器。

最后注册内置的后置处理器。

最后一步是检查 Bean 中有没有 ApplicationListenerDetector,如果有就做相应的操作。

目前只在 Bean 中保存了后置处理器,并不执行这些后置处理器。

7、initMessageSource

该方法是用于做消息绑定和消息解析等操作的。

protected void initMessageSource() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
		this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
		// Make MessageSource aware of parent MessageSource.
		if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
			HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
			if (hms.getParentMessageSource() == null) {
				// Only set parent context as parent MessageSource if no parent MessageSource
				// registered already.
				hms.setParentMessageSource(getInternalParentMessageSource());
			}
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Using MessageSource [" + this.messageSource + "]");
		}
	}
	else {
		// Use empty MessageSource to be able to accept getMessage calls.
		DelegatingMessageSource dms = new DelegatingMessageSource();
		dms.setParentMessageSource(getInternalParentMessageSource());
		this.messageSource = dms;
		beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
		}
	}
}
  1. 首先获取 beanFactory
  2. 看一下有没有 messageSource 这个组件,如果有就直接赋值,没有就创建一个默认的;
  3. MessageSource 接口中可以根据 key 值获取到国际化配置文件中的某个属性信息。
  4. 最后将该组件注册到容器中。

8、initApplicationEventMulticaster

初始化 事件派发器

protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		this.applicationEventMulticaster =
				beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	else {
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
					"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
		}
	}
}
  1. 首先获取 BeanFactory
  2. 然后从容器中获取 ApplicationEventMulticaster
  3. 如果有就直接赋值,没有就创建一个默认的 SimpleApplicationEventMulticaster

9、onRefresh

该方法没有实现,留给子类,在容器刷新的时候可以自定义逻辑。

protected void onRefresh() throws BeansException {
	// For subclasses: do nothing by default.
}

10、registerListeners

将项目中所有的 ApplicationListener 都注册到容器中。

protected void registerListeners() {
	// Register statically specified listeners first.
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		getApplicationEventMulticaster().addApplicationListener(listener);
	}
	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let post-processors apply to them!
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}
	// Publish early application events now that we finally have a multicaster...
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (earlyEventsToProcess != null) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}
  1. 从容器中拿到所有的 ApplicationListener
  2. 将每个监听器添加到事件派发器中。
  3. 派发之前步骤产生的事件;

11、finishBeanFactoryInitialization

这一步是最重要的,他负责初始化所有剩下的单实例 Bean。

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	。。。
	// Stop using the temporary ClassLoader for type matching.
	beanFactory.setTempClassLoader(null);
	// Allow for caching all bean definition metadata, not expecting further changes.
	beanFactory.freezeConfiguration();
	// 初始化剩下的单实例 Bean
	beanFactory.preInstantiateSingletons();
}

11.0、preInstantiateSingletons

进入到 org.springframework.beans.factory.support.DefaultListableBeanFactory # preInstantiateSingletons 方法中了。

@Override
public void preInstantiateSingletons() throws BeansException {
	if (logger.isTraceEnabled()) {
		logger.trace("Pre-instantiating singletons in " + this);
	}
	// 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.
	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) {
					final 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) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}

首先获取到所有的 Bean,然后依次进行初始化和创建对象。

然后获取 Bean 的定义信息 getMergedLocalBeanDefinition,判断一下,如果 Bean 不是抽象的,是单实例的,不是懒加载的,就会进入下面的逻辑。

如果不是工厂对象,就是调用 getBean 去创建对象。

然后来到 org.springframework.beans.factory.support.AbstractBeanFactory # getBean 方法:

@Override
public Object getBean(String name) throws BeansException {
	return doGetBean(name, null, null, false);
}

先获取缓存中保存的单实例 Bean,所有创建过的单实例 Bean 都会被缓存起来,缓存中获取不到,就开始 Bean 的创建流程。

final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();

先创建该 Bean 依赖的所有的其他 Bean。

然后启动单实例 Bean 的创建流程。

createBean(beanName, mbd, args)
createBean 的部分实现:

try {
	// Give BeanPostProcessors a chance to return a proxy instead of the target bean ins
	1、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 {
	2、Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	
	if (logger.isTraceEnabled()) {
		logger.trace("Finished creating instance of bean '" + beanName + "'");
	}
	return beanInstance;
}

resolveBeforeInstantiation

进入到 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory # createBean 方法,该方法首先调用:

Object bean = resolveBeforeInstantiation(beanName, mbdToUse);

这一步是让后置处理器先拦截返回代理对象。

正常的后置处理器是在 Bean 创建对象的时候拦截,但是现在还没有创建对象呢,所以这个后置处理器应该是 InstantiationAwareBeanPostProcessor 类型的后置处理器。

@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
	Object bean = null;
	if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
		// Make sure bean class is actually resolved at this point.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			Class<?> targetType = determineTargetType(beanName, mbd);
			if (targetType != null) {
				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
				if (bean != null) {
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
				}
			}
		}
		mbd.beforeInstantiationResolved = (bean != null);
	}
	return bean;
}

这里又调用了 applyBeanPostProcessorsBeforeInstantiation 方法。

@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
	for (BeanPostProcessor bp : getBeanPostProcessors()) {
		if (bp instanceof InstantiationAwareBeanPostProcessor) {
			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
			Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
			if (result != null) {
				return result;
			}
		}
	}
	return null;
}

该方法先去判断是不是 InstantiationAwareBeanPostProcessor 类型的,如果是就调用他的 postProcessBeforeInstantiation 方法,如果该方法有返回值还会调用 postProcessAfterInitialization 方法。

doCreateBean

如果 resolveBeforeInstantiation 没有返回代理对象,那么就要调用 doCreateBean 方法创建 Bean 了。

try {
	// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
	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 {
	Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	if (logger.isTraceEnabled()) {
		logger.trace("Finished creating instance of bean '" + beanName + "'");
	}
	return beanInstance;
}

跟进去 doCreateBean 方法:

if (instanceWrapper == null) {
	instanceWrapper = createBeanInstance(beanName, mbd, args);
}

调用了 createBeanInstance 方法,这个方法是依赖注入的核心,不往下聊了,只需要知道在这个方法中会利用工厂方法或者对象的构造器创建出 Bean 实例。

执行完 doCreateBean 之后,通过 applyMergedBeanDefinitionPostProcessors 方法调用 MergedBeanDefinitionPostProcessorpostProcessMergedBeanDefinition,他是在创建实例对象之后执行。

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

现在已经创建完 Bean 实例了,下面进行初始化,初始化的第一步是先进行属性赋值 populateBean

// Initialize the bean instance.
Object exposedObject = bean;
try {
	populateBean(beanName, mbd, instanceWrapper);
	exposedObject = initializeBean(beanName, exposedObject, mbd);
}

在属性赋值的时候会看一下是不是某一个后置处理器:

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
	for (BeanPostProcessor bp : getBeanPostProcessors()) {
		if (bp instanceof InstantiationAwareBeanPostProcessor) {
			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
			if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
				continueWithPropertyPopulation = false;
				break;
			}
		}
	}
}

拿到 InstantiationAwareBeanPostProcessor 后置处理器:

  1. 执行 postProcessAfterInstantiation
  2. 执行 postProcessPropertyValues
  3. 执行 applyPropertyValues:属性赋值

然后进行初始化 initializeBean

  1. 执行 Aware 接口方法:invokeAwareMethods
  2. 后置处理器初始化之前:applyBeanPostProcessorsBeforeInitialization:执行所有的后置处理器的 postProcessBeforeInitialization 方法;
  3. 执行初始化方法:invokeInitMethods
    • 是否是 InitializingBean 接口的实现:执行接口规定的初始化;
    • 是否自定义初始化方法;
  4. 后置处理器初始化之后:applyBeanPostProcessorsAfterInitialization:执行所有的后置处理器的 postProcessAfterInitialization 方法。
applyBeanPostProcessorsBeforeInitialization 方法的实现如下:

for (BeanPostProcessor processor : getBeanPostProcessors()) {
	Object current = processor.postProcessBeforeInitialization(result, beanName);
	if (current == null) {
		return result;
	}
	result = current;
}

最后注册 Bean 的销毁方法,到此为止 doCreateBean 方法结束。

所有的 Bean 都利用 getBean 创建完成之后,检查所有的 Bean 是否是 SmartInitializingSingleton 接口的,如果是就执行 afterSingletonsInstantiated 方法。

// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
	Object singletonInstance = getSingleton(beanName);
	if (singletonInstance instanceof SmartInitializingSingleton) {
		final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				smartSingleton.afterSingletonsInstantiated();
				return null;
			}, getAccessControlContext());
		}
		else {
			smartSingleton.afterSingletonsInstantiated();
		}
	}
}

12、finishRefresh

完成 BeanFactory 的初始化创建工作,IOC 容器就创建完成。

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. initLifecycleProcessor:初始化生命周期相关的后置处理器;先在容器中找 LifecycleProcessor 相关的组件,如果找到就赋值,没找到就创建一个默认的 DefaultLifecycleProcessor
  2. onRefresh:拿到刚才的 LifecycleProcessor ,调用它的刷新方法。
  3. publishEvent:发布事件

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 思科模拟器:实验五——高级路由实验

    (1) 理解路由表 (2) 掌握静态路由和动态路由的配置 (3) 理解 RIP 和 OSPF 协议的工作过程

    wsuo
  • Spring MVC 整合 Servlet 3.0

    根据 Servlet 3.0 的新特性,web 容器启动的时候会扫描每个 jar 包下的 /META-INF/services/javax.servlet.Se...

    wsuo
  • 代理工厂的简单应用

    在 Service 中调用 Dao 层,必须要 new 一个 Dao 对象,在 Controller 中也是如此调用 Service 层。

    wsuo
  • 面试Spring IOC

    所谓的IoC容器就是指的Spring中Bean工厂里面的Map存储结构(存储了Bean的实例)

    小土豆Yuki
  • Spring IOC 源码分析

    Spring 最重要的概念是 IOC 和 AOP,本篇文章其实就是要带领大家来分析下 Spring 的 IOC 容器。

    黎明大大
  • SpringBoot整合自定义注解

    之前我们学习了java的自定义注解,而且我们可以非常方便的进行注解值到实体真实值得转变。那么我们如何将这些标记值设置到spring容器中?那么我们就需要了解一些...

    程序员_备忘录
  • LeetCode Longest Palindromic Substring

    Given a string s, find the longest palindromic substring in s. You may assume th...

  • 终于让采集侠自动采集了

    用织梦采集侠一段时间了,觉得这个插件真的不错,尤其是新版本,可以结合DEDE自动的采集规则来进行采集。一下采集功能就非常强大了。

    用户1191760
  • R语言写2048游戏

           2048 是一款益智游戏,只需要用方向键让两两相同的数字碰撞就会诞生一个翻倍的数字,初始数字由 2 或者 4 构成,直到游戏界面全部被填满,游戏结...

    用户1680321
  • R条件语句

    但如果你有一长串 if 语句,那么就要考虑重写了。重写的一种方法是使用 switch() 函数, 它先对第一个参数求值,然后按照名称或位置在后面的参数列表中匹...

    生信编程日常

扫码关注云+社区

领取腾讯云代金券