--- title: Spring源码系列-第2章-后置工厂处理器和Bean生命周期 tags: - Spring源码 categories: - Spring - 源码V1 keywords: Spring,框架,spring源码 description: 开始讲最重要的xxxPostProcessor cover: 'https://npm.elemecdn.com/lql_static@latest/logo/spring.png' abbrlink: 41fb8d9e date: 2021-12-21 20:21:58 --- # 第2章-后置工厂处理器和Bean生命周期 > 后置工厂处理器属于后置处理器,后置处理器是Spring最核心的部分,Spring几乎所有的附加功能全由它完成。 ## 什么是BeanPostProcessor? ```java public interface BeanPostProcessor { /** * Apply this {@code BeanPostProcessor} to the given new bean instance before any bean * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} * or a custom init-method). The bean will already be populated with property values. * The returned bean instance may be a wrapper around the original. *
The default implementation returns the given {@code bean} as-is. * @param bean the new bean instance * @param beanName the name of the bean * @return the bean instance to use, either the original or a wrapped one; * if {@code null}, no subsequent BeanPostProcessors will be invoked * @throws org.springframework.beans.BeansException in case of errors * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet */ @Nullable default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } /* 将这个{@code BeanPostProcessor}应用到给定的新bean实例在任何bean初始化回调之后 (如InitializingBean的{@code afterPropertiesSet} 或自定义初始化方法)。bean将已经被属性值填充。返回的bean实例可能是原始bean的包装器。 */ /** * Apply this {@code BeanPostProcessor} to the given new bean instance after any bean * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} * or a custom init-method). The bean will already be populated with property values. * The returned bean instance may be a wrapper around the original. *
In case of a FactoryBean, this callback will be invoked for both the FactoryBean * instance and the objects created by the FactoryBean (as of Spring 2.0). The * post-processor can decide whether to apply to either the FactoryBean or created * objects or both through corresponding {@code bean instanceof FactoryBean} checks. *
This callback will also be invoked after a short-circuiting triggered by a * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method, * in contrast to all other {@code BeanPostProcessor} callbacks. *
The default implementation returns the given {@code bean} as-is.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
```
这个是要干什么呢?BeanPostProcessor类中的注释本身没有说的太明白,我们可以来看下另一个后置处理器
```java
@FunctionalInterface
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
```
核心就是我们对于传进来的参数,可以**修改,覆盖,添加**它的东西。对于BeanPostProcessor来说,传进来的参数是`(Object bean, String beanName)` ,它都已经把bean传给你了,这意味着我们可以修改传进来的Bean的任何东西。不管你是事务也好,AOP也好,都是通过这些个后置处理器来添加这些额外功能的。
BeanPostProcessor:后置增强普通的Bean组件
BeanFactoryPostProcessor:后置增强BeanFactory,也就是增强Bean工厂
### BeanFactoryPostProcessor的接口关系
### BeanPostProcessor接口关系
DestructionAwareBeanPostProcessor接口是跟销毁有关的,我们这里不分析
> 之前说过,分析源码时,优先看接口继承关系,好的框架大部分都是遵循**基于接口而非实现**这一设计思想。
## 什么是InitializingBean?
```java
public interface InitializingBean {
//翻译: 该方法允许bean实例在设置了所有bean属性后对其总体配置和最终初始化执行验证
/**
* Invoked by the containing {@code BeanFactory} after it has set all bean properties
* and satisfied {@link BeanFactoryAware}, {@code ApplicationContextAware} etc.
*
This method allows the bean instance to perform validation of its overall
* configuration and final initialization when all bean properties have been set.
* @throws Exception in the event of misconfiguration (such as failure to set an
* essential property) or if initialization fails for any other reason
*/
void afterPropertiesSet() throws Exception;
}
```
1. Bean组件初始化以后对组件进行后续设置,因为它没有参数传进来,它改变不了什么东西,它的目的在于额外处理。
2. 后面我们会讲到BeanPostProcessor主要用于Spring中大部分组件都会用到的功能处理。而InitializingBean是单组件处理(做一些额外处理),最好的例子就是SpringMVC里的一些组件,后面讲。
## 测试类
### MyBeanPostProcessor
```java
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public MyBeanPostProcessor(){
System.out.println("MyBeanPostProcessor...");
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor...postProcessAfterInitialization..."+bean+"==>"+beanName);
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor...postProcessBeforeInitialization..."+bean+"==>"+beanName);
return bean;
}
}
```
### MyInstantiationAwareBeanPostProcessor
```java
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
public MyInstantiationAwareBeanPostProcessor(){
System.out.println("MyInstantiationAwareBeanPostProcessor...");
}
public Object postProcessBeforeInstantiation(Class> beanClass, String beanName) throws BeansException {
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessBeforeInstantiation=>"+beanClass+"--"+beanName);
return null;
}
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessAfterInstantiation=>"+bean+"--"+beanName);
return true;
}
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {
System.out.println("MyInstantiationAwareBeanPostProcessor...postProcessProperties=>"+bean+"--"+beanName);
return null;
}
}
```
### MyMergedBeanDefinitionPostProcessor
```java
@Component
public class MyMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor {
public MyMergedBeanDefinitionPostProcessor(){
System.out.println("MyMergedBeanDefinitionPostProcessor...");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessBeforeInitialization...=>"+bean+"--"+beanName);
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessAfterInitialization..=>"+bean+"--"+beanName);
return null;
}
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {
System.out.println("MyMergedBeanDefinitionPostProcessor...postProcessMergedBeanDefinition..=>"+beanName+"--"+beanType+"---"+beanDefinition);
}
@Override
public void resetBeanDefinition(String beanName) {
System.out.println("MyMergedBeanDefinitionPostProcessor...resetBeanDefinition.."+beanName);
}
}
```
### MySmartInstantiationAwareBeanPostProcessor
```java
@Component
public class MySmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor {
public MySmartInstantiationAwareBeanPostProcessor(){
System.out.println("MySmartInstantiationAwareBeanPostProcessor...");
}
public Class> predictBeanType(Class> beanClass, String beanName) throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...predictBeanType=>"+beanClass+"--"+beanName);
return null;
}
public Constructor>[] determineCandidateConstructors(Class> beanClass, String beanName)
throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...determineCandidateConstructors=>"+beanClass+"--"+beanName);
return null;
}
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
System.out.println("MySmartInstantiationAwareBeanPostProcessor...getEarlyBeanReference=>"+bean+"--"+beanName);
return bean;
}
}
```
### MyInitializingBean
```java
/**
* 生命周期接口
*/
@Component
public class MyInitializingBean implements InitializingBean {
public MyInitializingBean(){
System.out.println("MyInitializingBean....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("MyInitializingBean...afterPropertiesSet...");
}
}
```
### MyBeanFactoryPostProcessor
```java
/**
* BeanFactory的后置处理器
*/
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public MyBeanFactoryPostProcessor(){
System.out.println("MyBeanFactoryPostProcessor...");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("BeanFactoryPostProcessor....postProcessBeanFactory==>"+beanFactory);
}
}
```
### MyBeanDefinitionRegistryPostProcessor
```java
@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
public MyBeanDefinitionRegistryPostProcessor(){
System.out.println("MyBeanDefinitionRegistryPostProcessor");
}
@Override //紧接着执行
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor....postProcessBeanFactory...");
}
@Override //先执行的
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("MyBeanDefinitionRegistryPostProcessor...postProcessBeanDefinitionRegistry...");
//增强bean定义信息的注册中心,比如自己注册组件
}
}
```
### Cat
```java
@Component
public class Cat {
public Cat(){
System.out.println("cat被创建了...");
}
private String name;
@Value("${JAVA_HOME}") //自动赋值功能
public void setName(String name) {
System.out.println("cat....setName正在赋值调用....");
this.name = name;
}
public String getName() {
return name;
}
}
```
### beans2.xml
```java
Higher values are interpreted as lower priority. As a consequence,
* the object with the lowest value has the highest priority (somewhat
* analogous to Servlet {@code load-on-startup} values).
* Same order values will result in arbitrary sort positions for the
* affected objects.java
* @return the order value
* @see #HIGHEST_PRECEDENCE
* @see #LOWEST_PRECEDENCE
*/
int getOrder(); //根据注释我们可以知道返回的int值越小优先级越高,反之越低
}
```
1. 从上面的源码中我们可以看到PriorityOrdered的代码在Ordered代码前面,获取完PriorityOrdered的BeanDefinitionRegistryPostProcessor就直接invokeBeanDefinitionRegistryPostProcessors执行了,所以如果有多个组件,这些组件有些实现了PriorityOrdered ,有些实现了Ordered。实现了PriorityOrdered 的组件执行顺序永远大于实现了Ordered的组件。
2. 即使同时实现了 PriorityOrdered 和Ordered,也是以 PriorityOrdered为准。
#### 执行postProcessBeanDefinitionRegistry方法
##### Debug调用栈
### BeanDefinitionRegistryPostProcessor
#### 执行无参构造
##### Debug调用栈
##### AbstractApplicationContext#refresh()
> 和以前一样,目前用不到的源码都省略,最后会逐渐给一个完整的源码注释。
```java
@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.
// 工厂创建:BeanFactory第一次开始创建的时候,有xml解析逻辑。
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");
//工厂增强:执行所有的BeanFactory后置增强器;利用BeanFactory后置增强器对工厂进行修改或者增强,配置类会在这里进行解析。
invokeBeanFactoryPostProcessors(beanFactory);
//注册所有的Bean的后置处理器 Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
//...
// Instantiate all remaining (non-lazy-init) singletons.
//bean创建;完成 BeanFactory 初始化。(工厂里面所有的组件都好了)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
}
}
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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
```
##### PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()
> 此类没有省略代码
```java
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List
下面那个是Spring默认提供的后置处理器,我们后面再讲。
###### PriorityOrdered或Ordered实现排序
那么这些后置处理器的顺序Spring是如何排序的呢?我们又该怎样自定义BeanPostProcessor的顺序?我们可以通过实现PriorityOrdered或Ordered这两接口来自定义BeanPostProcessor的执行顺序。
PriorityOrdered是个空类,啥也没有
```java
public interface PriorityOrdered extends Ordered {
}
```
我们只能看他的父类
```java
public interface Ordered {
/**
* Useful constant for the highest precedence value.
* @see java.lang.Integer#MIN_VALUE
*/
int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
/**
* Useful constant for the lowest precedence value.
* @see java.lang.Integer#MAX_VALUE
*/
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
/**
* Get the order value of this object.
*
从PostProcessorRegistrationDelegate 142行开始走不同的调用,代码在上面有注释
##### PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()
```java
private static void invokeBeanDefinitionRegistryPostProcessors(
Collection extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {
for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
postProcessor.postProcessBeanDefinitionRegistry(registry);//在这里就多态调用我们自定义的方法,也可以说是模板模式
postProcessBeanDefRegistry.end();
}
}
```
#### 执行postProcessBeanFactory
##### Debug调用栈
##### PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors()
```java
private static void invokeBeanFactoryPostProcessors(
Collection extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {
for (BeanFactoryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
.tag("postProcessor", postProcessor::toString);
postProcessor.postProcessBeanFactory(beanFactory); //一样的多态调用我们自定义的方法
postProcessBeanFactory.end();
}
}
```
### BeanFactoryPostProcessor
#### 执行无参构造
##### Debug调用栈
#### 执行postProcessBeanFactory
##### Debug调用栈
代码注释也是上面那个,BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor执行逻辑基本一样
> 上面两个都是BeanFactoryPostProcessor,也就是增强Bean工厂的
### Spring内部的工厂增强了什么?-简单说明
我们用注解版启动一下
```java
public class AnnotationMainTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person bean = applicationContext.getBean(Person.class);
ApplicationContext context = bean.getContext();
System.out.println(context == applicationContext);
}
}
```
```java
@ComponentScan("cn.imlql.spring")
@Configuration
public class MainConfig {
public MainConfig(){
System.out.println("MainConfig...创建了....");
}
}
```
从这一步进来
#### PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors()
F7进入
#### ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry()
ConfigurationClassPostProcessor配置类的后置处理
#### ConfigurationClassPostProcessor#processConfigBeanDefinitions()
```java
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List
最终上面的调用栈会`parser.parse(candidates);` 一直调到下面的`ConfigurationClassParser#processConfigurationClass()`,这里也是简单过一下,后面还会再讲。
#### ConfigurationClassParser#processConfigurationClass()
配置类解析的核心方法
```java
protected void processConfigurationClass(ConfigurationClass configClass, Predicate