Spring initializeBean source code analysis

One, overview of initializeBean method

The initializeBean() method in Spring is the last step of the doCreateBean method trilogy. After the initializeBean() is completed, the entire bean creation process is complete. Let’s take a look at the bean creation process in the doCreateBean() method trilogy: instantiation (CreateBeanInstance), populate properties (populateBean), initialize (initializeBean).

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
		implements AutowireCapableBeanFactory {
    
    
    protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {
    
    

        // 省略部分代码....
		
		// 第一步:实例化bean
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	
		// 为避免后期循环依赖,提前曝露ObjectFactory到第三级缓存中。
		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        
        // 第二步:填充属性
		populateBean(beanName, mbd, instanceWrapper);
        
		// 第三步:执行初始化逻辑
		exposedObject = initializeBean(beanName, exposedObject, mbd);
		
	}
}

This article mainly analyzes the initialization of initializeBean. For the first two steps of "instancing" and "filling attributes", please refer to:

Spring instantiation (createBeanInstance) source code analysis

Spring attribute populateBean source code analysis


The initialization of initializeBean is mainly divided into the following steps:

  1. Execute the aware interface invokeAwareMethods.
  2. Execute the postProcessBeforeInitialization() method of BeanPostProcessor.
  3. Execute the initialization method invokeInitMethods.
  4. Execute the postProcessAfterInitialization() method of BeanPostProcessor.
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    
    
		
		// Aware接口处理器,调用BeanNameAware、BeanClassLoaderAware、beanFactoryAware
		invokeAwareMethods(beanName, bean);
		
		// 调用BeanPostProcessor的postProcessBeforeInitialization方法。
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		
		// 调用初始化方法,先调用bean的InitializingBean接口方法,后调用bean的自定义初始化方法
		invokeInitMethods(beanName, wrappedBean, mbd);
		
    	// 调用BeanPostProcessor的applyBeanPostProcessorsAfterInitialization方法。
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

		//返回包装后的Bean
		return wrappedBean;
	}

We can see from the above that both the postProcessBeforeInitialization() method and postProcessAfterInitialization() method of the beanPostProcessor interface can modify or replace the final bean.

If we configure an Aop proxy, we will create the bean proxy object when the postProcessAfterInitialization() method of the AbstractAutoProxyCreator class is executed, and put the proxy object into the bean container.

Second, execute the aware interface invokeAwareMethods

This method is to determine whether the current bean implements the BeanNameAware, BeanClassLoaderAware, and BeanFactoryAware interfaces. If it is implemented, call back the corresponding method. Relatively simple, there is nothing to say, just look at the source code:

private void invokeAwareMethods(String beanName, Object bean) {
    
    
		//如果 bean 是 Aware 实例
		if (bean instanceof Aware) {
    
    
			//如果bean是BeanNameAware实例
			if (bean instanceof BeanNameAware) {
    
    
				//调用 bean 的setBeanName方法
				((BeanNameAware) bean).setBeanName(beanName);
			}
			//如果bean是 BeanClassLoaderAware 实例
			if (bean instanceof BeanClassLoaderAware) {
    
    
				//获取此工厂的类加载器以加载Bean类(即使无法使用系统ClassLoader,也只能为null)
				ClassLoader bcl = getBeanClassLoader();
				if (bcl != null) {
    
    
					//调用 bean 的 setBeanClassLoader 方法
					((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
				}
			}
			//如果bean是 BeanFactoryAware 实例
			if (bean instanceof BeanFactoryAware) {
    
    
				// //调用 bean 的 setBeanFactory 方法
				((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
			}
		}
	}

Three, execute the postProcessBeforeInitialization() method of BeanPostProcessor

The postProcessBeforeInitialization() method will be called before the init method is executed, and the postProcessBeforeInitialization() method is called by traversing the beanPostProcessors collection.

	public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
			throws BeansException {
    
    

		//初始化返回结果为existingBean
		Object result = existingBean;
		//遍历 该工厂创建的bean的BeanPostProcessors列表
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
    
    
			// postProcessBeforeInitialization:在任何Bean初始化回调之前(如初始化Bean的afterPropertiesSet或自定义的init方法)
			// 将此BeanPostProcessor 应用到给定的新Bean实例。Bean已经填充了属性值。返回的Bean实例可能时原始Bean的包装器。
			// 默认实现按原样返回给定的 Bean
			Object current = processor.postProcessBeforeInitialization(result, beanName);
			// 如果 current为null
			if (current == null) {
    
    
				//直接返回result,中断其后续的BeanPostProcessor处理
				return result;
			}
			//让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
			result = current;
		}
		//返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
		return result;
	}

1. ApplicationContextAwareProcessor calls the Aware interface method

The main completion is to determine whether the current bean implements EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware, and ApplicationContextAware interfaces, and if implemented, call its methods.

class ApplicationContextAwareProcessor implements BeanPostProcessor {
    
    
     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
    
    
			return bean;
		}

		AccessControlContext acc = null;

		if (System.getSecurityManager() != null) {
    
    
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
    
    
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    
    
				// 检测bean上是否实现了某个aware接口,有的话进行相关的调用
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
    
    
			invokeAwareInterfaces(bean);
		}

		return bean;
	}   
}

2. ConfigurationClassPostProcessor calls the ImportAware interface method

If the bean implements the ImportAware interface, the annotation information of the bean will be set:

	public Object postProcessBeforeInitialization(Object bean, String beanName) {
    
    
			if (bean instanceof ImportAware) {
    
    
				ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
				AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
				if (importingClass != null) {
    
    
					((ImportAware) bean).setImportMetadata(importingClass);
				}
			}
			return bean;
		}

3. InitDestroyAnnotationBeanPostProcessor calls life cycle methods modified by annotations

In doCreateBean, after the instantiation of createBeanInstance is completed, the applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName) method will be executed before populateBean filling properties are executed:

	protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
    
    
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
    
    
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
    
    
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

The purpose is to allow beanPostProcessor to modify the merged beanDefinition, which will execute the postProcessMergedBeanDefinition() method of the InitDestroyAnnotationBeanPostProcessor class:

	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    
    
		// 调用方法获取生命周期元数据并保存
		LifecycleMetadata metadata = findLifecycleMetadata(beanType);
		// 验证相关方法
		metadata.checkConfigMembers(beanDefinition);
	}

The methods annotated by @PostContruct and @PreDestroy contained in the current bean will be obtained and stored in the map of lifecycleMetadataCache.


Therefore, the postProcessBeforeInitialization() method of the InitDestroyAnnotationBeanPostProcessor class will use reflection to call the method cached in the lifecycleMetadataCache and modified by the @PostContruct annotation:

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
    
    
			metadata.invokeInitMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
    
    
			throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
		}
		catch (Throwable ex) {
    
    
			throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
		}
		return bean;
	}

Fourth, execute the initialization method invokeInitMethods

If the bean implements the InitializingBean interface, the afterPropertiesSet method of the InitializingBean interface is executed first.

Then execute the init-method method set by xml or annotation.

protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
			throws Throwable {
    
    
    
    // 省略部分代码...
    
	// 调用bean的afterPropertiesSet方法
	((InitializingBean) bean).afterPropertiesSet();
			
	// 在bean上调用指定的自定义init方法
	invokeCustomInitMethod(beanName, bean, mbd);
			
}

Five, execute the postProcessAfterInitialization() method of BeanPostProcessor

Traverse the beanPostProcessors collection and execute the post processor of BeanPostProcessor:

	public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {
    
    

		//初始化结果对象为result,默认引用existingBean
		Object result = existingBean;
		//遍历该工厂创建的bean的BeanPostProcessors列表
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
    
    
			//回调BeanPostProcessor#postProcessAfterInitialization来对现有的bean实例进行包装
			Object current = processor.postProcessAfterInitialization(result, beanName);
			//一般processor对不感兴趣的bean会回调直接返回result,使其能继续回调后续的BeanPostProcessor;
			// 但有些processor会返回null来中断其后续的BeanPostProcessor
			// 如果current为null
			if (current == null) {
    
    
				//直接返回result,中断其后续的BeanPostProcessor处理
				return result;
			}
			//让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
			result = current;
		}
		//返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
		return result;
	}

1. AbstractAutoProxyCreator generates aop proxy objects

If an aop proxy is used, a proxy object will be generated here to replace the native bean object.

	public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    
    
		if (bean != null) {
    
    
			// 根据给定bean的name和class构建出一个key
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
    
    
				// 如果它需要被代理,则需要封装指定的bean
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}

First check whether it exists in the earlyProxyReferences cache. If it does, it means that it has been processed. If it does not exist, consider whether it needs to be proxied. If necessary, create a proxy object (encapsulate the native bean).

2. ApplicationListenerDetector detects whether the bean implements the ApplicationListener interface

If the bean is singleton and implements the ApplicationListener interface, it is added to the applicationEventMulticaster in the multicaster.

public Object postProcessAfterInitialization(Object bean, String beanName) {
    
    
		if (bean instanceof ApplicationListener) {
    
    
			// 判断当前bean是否是单例,如果是的话,直接添加到容器的监听器集合中
			Boolean flag = this.singletonNames.get(beanName);
			if (Boolean.TRUE.equals(flag)) {
    
    
				// 添加到容器的监听器集合中
				this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
			}
			// 如果不是单例的,并且又是一个嵌套的bean,那么打印日志,提示内嵌的bean只有在单例的情况下才能作为事件监听器
			
		}
		return bean;
	}

Six, summary

Life cycle execution order:

  1. @PostConstruct annotation modification method
  2. The afterPropertiesSet() method of the InitializingBean interface
  3. The method specified by init-method
  4. @PreDestroy annotation modification method
  5. The destroy() method of the DisposableBean interface
  6. The method specified by destruction-method

Guess you like

Origin blog.csdn.net/u013277209/article/details/110651253