欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【spring源码】Spring中BeanPostProcessor何时生效

程序员文章站 2022-07-14 16:13:53
...

Spring中BeanPostProcessor何时生效

在Spring中我们有时会使用BeanPostProcessor来增强我们的bean,但BeanPostProcessor又是什么时候被使用的呢,接下来我们一起来跟着spring的源码走一下

1.编写一个入口类

public class Entry {

	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
	}
}

2. 点击进入构造方法

	public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		//1. 在此处向BeanDefinition中注册了6个注解处理器
		//2. 此处初始化了系统属性以及环境变量
		//3. 注册了注解过滤器
		this();
		//紧紧注册配置类的BeanDefinition信息到BeanFactory
		register(annotatedClasses);
		//真正创建对象并调用BeanPostProcessor处理器的方法
		refresh();
	}

3. 进入refresh方法

  • 此处找到方法中的finishBeanFactoryInitialization,这里就是具体实列化Bean的地方
@Override
	public void refresh() throws BeansException, IllegalStateException {
		.....................

			try {
		.....................

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

				// Last step: publish corresponding event.
				finishRefresh();
			}
		...................
	}

4. 进入finishBeanFactoryInitialization方法

  • 此处最后一行方法为初始化Bean,找到该方法的实现类DefaultListableBeanFactory并进入方法
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();

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

5. preInstantiateSingletons方法中

  • 最后一个else中的getBean为具体创建Bean代码,点击进入并进入doGetBean方法
public void preInstantiateSingletons() throws BeansException {
		.....................
						}
						else {
							isEagerInit = (factory instanceof SmartFactoryBean &&
									((SmartFactoryBean<?>) factory).isEagerInit());
						}
						if (isEagerInit) {
							getBean(beanName);
						}
					}
				}
				else {
					getBean(beanName);
				}
			}
		}

6.AbstractBeanFactory类的doGetBean方法中

  • 找到314-328行代码中的createBean方法
				// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						try {
							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);
				}

7.找到AbstractAutowireCapableBeanFactory类

  • 在此类中找到createBean方法,再次方法中可以找到doCreateBean方法调用
try {
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isDebugEnabled()) {
				logger.debug("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}

8.AbstractAutowireCapableBeanFactory

  • 在此类中的doCreateBean方法里面我们可以找到如下代码
		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}

9.进入AbstractAutowireCapableBeanFactory类

  • 在方法initializeBean中可以找到applyBeanPostProcessorsBeforeInitialization方法调用
		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

10. 方法applyBeanPostProcessorsBeforeInitialization就是所有的增强处理的地方

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

		Object result = existingBean;
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
相关标签: spring