在这之前我们先来看下refresh()
方法,它完整的描述了整个ApplicationContext的初始化过程。这里看起来更像是对容器进行初始化的模板或者提纲。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 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.
// BeanFactory的预准备工作(设置ClassLoader、表达式解析器等)
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 注册BeanFactory的后置处理器
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 执行BeanFactory 的后置处理器(包括解析配置类,加载业务Bean的定义到容器)
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册Bean的后置处理器,在Bean的创建和初始化过程中调用
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 初始化上下文中的消息
initMessageSource();
// Initialize event multicaster for this context.
// 初始化上下文中的事件机制
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化其他特殊Bean
onRefresh();
// Check for listener beans and register them.
// 检查监听Bean并且将这些Bean向容器注册
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有的单例且为非懒加载的Bean,并向容器注册这些Bean(包括业务Bean)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.、
// 发布容器事件,结束refresh过程
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.
// 防止Bean资源占用,在异常处理中,销毁已经砸前面生成的Bean
destroyBeans();
// Reset 'active' flag.
// 重置 'active' 标志
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();
}
}
}
-
registerBeanPostProcessors()
:完成了所有后置处理器 BeanPostProcessor 的实例化,并注册到容器。 -
finishBeanFactoryInitialization(beanFactory);
:方法完成了对所有业务单例Bean的初始化,并注册到容器。
registerBeanPostProcessors 注册所有后置处理器
调用链路:
registerBeanPostProcessors:188, PostProcessorRegistrationDelegate (org.springframework.context.support)
registerBeanPostProcessors:703, AbstractApplicationContext (org.springframework.context.support)
refresh:528, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
// 完成了所有后置处理器 BeanPostProcessor 的实例化,并注册到容器。
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 从容器中找出所有的后置处理器的名称
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List priorityOrderedPostProcessors = new ArrayList();
List internalPostProcessors = new ArrayList();
List orderedPostProcessorNames = new ArrayList();
List nonOrderedPostProcessorNames = new ArrayList();
// 对后置处理器进行分类 分为PriorityOrdered、Ordered和regular三类
for (String ppName : postProcessorNames) {
// PriorityOrdered 类
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 完成后置处理器的实例化
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// Order 类
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
// nonOrdered类
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 首先将实现PriorityOrdered接口的BeanPostProcessors注册到容器
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 其次将实现Ordered接口的BeanPostProcessors实例化并注册到容器
List orderedPostProcessors = new ArrayList();
for (String ppName : orderedPostProcessorNames) {
// 完成后置处理器的实例化
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 再次将常规的BeanPostProcessors实例化并注册到容器
List nonOrderedPostProcessors = new ArrayList();
for (String ppName : nonOrderedPostProcessorNames) {
// 完成后置处理器的实例化
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后从新将所有内部的BeanPostProcessors注册到容器
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 重新注册ApplicationListenerDetector后置处理器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
执行过程:
- 从容器中找出所有的后置处理器的名称
- 对后置处理器进行分类,分为PriorityOrdered、Ordered和regular三类
- 将实现PriorityOrdered接口的BeanPostProcessors实例化并注册到容器
- 将实现Ordered接口的BeanPostProcessors实例化并注册到容器
- 将常规的BeanPostProcessors实例化并注册到容器
- 从新将所有内部的BeanPostProcessors注册到容器
- 重新注册ApplicationListenerDetector后置处理器
PriorityOrdered继承自Ordered,但是并没有任何的增强。PriorityOrdered仅仅是一个标志,从上面的源代码我们可以看出,不管
getOrder()
返回值的大小,PriorityOrdered的优先级始终高于Ordered。
finishBeanFactoryInitialization() 注册所有业务Bean
调用链路:
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation() 创建Bean的前置处理方法
InstantiationAwareBeanPostProcessor:这个后置处理器主要运行在在实例化Bean的前后,主要作用是对Bean的实例化进行扩展处理。
实例化之前调用 postProcessBeforeInstantiation() 方法,调用链路:
postProcessBeforeInstantiation:20, InitBeanInstantiationAwareBeanPostProcessor (com.xiaolyuh.init.destory)
applyBeanPostProcessorsBeforeInstantiation:1045, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
resolveBeforeInstantiation:1019, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:473, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
...
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 调用创建bean的前置方法 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
...
// 创建Bean实例并放到容器中
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
// 调用InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()方法
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;
}
doCreateBean() 创建Bean
调用链路:
doCreateBean:513, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// 实例化Bean
BeanWrapper instanceWrapper = null;
...
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
...
// 执行MergedBeanDefinitionPostProcessor后置处理器,运行时合并bean的定义(RootBeanDefinition)。
// 比如处理@Autowired、@Resource、@Vaule等注解
synchronized (mbd.postProcessingLock) {
...
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
...
}
...
// 初始化Bean实例
Object exposedObject = bean;
try {
// 设置属性值
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 初始化Bean
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);
}
}
...
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
...
return exposedObject;
}
创建Bean的过程:
- 实例化Bean
- 执行MergedBeanDefinitionPostProcessor后置处理器
- 设置属性值
- 初始化Bean实例
createBeanInstance() 实例化Bean
调用链路:
createBeanInstance:1069, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:513, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
...
// 确定是否需要调用特定构造函数
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 调用特定构造函数
return autowireConstructor(beanName, mbd, ctors, args);
}
// 调用无参构造函数
return instantiateBean(beanName, mbd);
}
// 反射调用无参构造函数创建实例
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
...
else {
// 通过反射创建实例
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 将实例包装成 BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
...
}
执行MergedBeanDefinitionPostProcessor后置处理器
MergedBeanDefinitionPostProcessor:他主要作用就是对Bean的定义进行合并,如解析Bean中的@Autowired
、@Resource
和@Vaule
等注解,并将其封装成成InjectedElement,如 AutowiredFieldElement
、AutowiredMethodElement
和ResourceElement
等。最后合并元数据信息到RootBeanDefinition.externallyManagedConfigMembers
上。
postProcessMergedBeanDefinition:298, CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)
applyMergedBeanDefinitionPostProcessors:1000, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:523, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {
super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
if (beanType != null) {
// 找到元数据信息
InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
// 校验并合并元数据信息
metadata.checkConfigMembers(beanDefinition);
}
}
// checkConfigMembers:70, InjectionMetadata (org.springframework.beans.factory.annotation)
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set checkedElements = new LinkedHashSet(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
// 合并元数据信息
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
if (logger.isDebugEnabled()) {
logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}
populateBean() 设置属性值
这其实就是@Autowired
注解对应后置处理器AutowiredAnnotationBeanPostProcessor
的执行流程。而主要起作用的是InstantiationAwareBeanPostProcessor
后置处理器,这里会先调用InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
方法,再调用InstantiationAwareBeanPostProcessor.postProcessPropertyValues()
方法。在InstantiationAwareBeanPostProcessor.postProcessPropertyValues()
方法中我们会将属性的值通过反射设置进去,下面是调用链路:
populateBean:1272, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:553, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
...
// 执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 如果该方法返回false,那么会阻断后面后置处理器的执行。
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
// 阻断后面后置处理器的执行。
if (!continueWithPropertyPopulation) {
return;
}
...
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
// 执行InstantiationAwareBeanPostProcessor.postProcessPropertyValues 使用反射给属性赋值
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs);
}
InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation ()
调用链路:
postProcessAfterInstantiation:308, CommonAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
populateBean:1272, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
源码:
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
postProcessAfterInstantiation 如果该方法返回false,那么会阻断后面后置处理器的执行。
InstantiationAwareBeanPostProcessor.postProcessPropertyValues()
在这个方法中我们会将属性的值通过反射设置进去,调用链路:
resolveCandidate:208, DependencyDescriptor (org.springframework.beans.factory.config)
doResolveDependency:1138, DefaultListableBeanFactory (org.springframework.beans.factory.support)
resolveDependency:1066, DefaultListableBeanFactory (org.springframework.beans.factory.support)
inject:585, AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement (org.springframework.beans.factory.annotation)
inject:88, InjectionMetadata (org.springframework.beans.factory.annotation)
postProcessPropertyValues:366, AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
populateBean:1272, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
源码:
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeanCreationException {
// 找到需要自动装配的元数据
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// 使用反射填充Bean
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
...
try {
// 获取属性值,如果设置也是Bean,那么会调用beanFactory.getBean(beanName, requiredType);方法,调用链路:
// resolveCandidate:208, DependencyDescriptor (org.springframework.beans.factory.config)
// doResolveDependency:1138, DefaultListableBeanFactory (org.springframework.beans.factory.support)
// resolveDependency:1066, DefaultListableBeanFactory (org.springframework.beans.factory.support)
// inject:585, AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement (org.springframework.beans.factory.annotation)
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
...
if (value != null) {
// 设置属性值
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
initializeBean() 初始化实例
初始化主要分为四步:
- 执行部分Spring Awar方法
- 执行BeanPostProcessors后置处理器的postProcessBeforeInitialization方法
- 执行自定义的初始化Bean方法,afterPropertiesSet()-> @Bean 注解的 initMethod 方法
- 执行BeanPostProcessors后置处理器的postProcessAfterInitialization方法
调用链路:
initializeBean:1621, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:555, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:202, AbstractBeanFactory (org.springframework.beans.factory.support)
invokeBeanFactoryPostProcessors:86, PostProcessorRegistrationDelegate (org.springframework.context.support)
invokeBeanFactoryPostProcessors:687, AbstractApplicationContext (org.springframework.context.support)
refresh:525, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
...
// 执行部分Spring Awar方法
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 执行BeanPostProcessors后置处理器的postProcessBeforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行自定义的初始化Bean方法,afterPropertiesSet()-> @Bean 注解的 initMethod 方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 执行BeanPostProcessors后置处理器的postProcessAfterInitialization方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
invokeAwareMethods() 执行部分Spring Awar方法
调用链路:
invokeAwareMethods:1644, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1621, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
源码:
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
- 先判断是否是实现了Aware接口
- 在判断具体实现了那个Aware接口
- 根据具体实现的Aware调用对应回调方法
BeanPostProcessors.postProcessBeforeInitialization() 后置处理器的前置方法执行
调用链路:
applyBeanPostProcessorsBeforeInitialization:407, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1626, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
源码:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
获取到所有BeanPostProcessors后置处理器,循环执行其postProcessBeforeInitialization方法,我们在上面说过BeanPostProcessors是有顺序的。
这里我们重点看ApplicationContextAwareProcessor和InitDestroyAnnotationBeanPostProcessor两个后置处理器postProcessBeforeInitialization方法的代码。
- ApplicationContextAwareProcessor主要实现了Spring Aware,上面
invokeAwareMethods()
方法执行力一部分Spring Aware的方法,剩下的Aware主要就是用ApplicationContextAwareProcessor来实现的。 - InitDestroyAnnotationBeanPostProcessor主要是实现了Bean的@PostConstruct和@PreDestroy方法。
ApplicationContextAwareProcessor.postProcessBeforeInitialization() 后置处理器的执行
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
...
invokeAwareInterfaces(bean);
...
return bean;
}
// 判断Bean是实现的那个Aware接口,然后调用对应的感知方法。
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
- 先判断是否是实现了Aware接口
- 在判断具体实现了那个Aware接口
- 根据具体实现的Aware调用对应回调方法
Aware的执行顺序:
- BeanNameAware
- BeanClassLoaderAware
- BeanFactoryAware
- EnvironmentAware
- EmbeddedValueResolverAware
- ResourceLoaderAware
- ApplicationEventPublisherAware
- MessageSourceAware
- ApplicationContextAware
InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization() 后置处理器的执行
调用链路:
postConstructstroy:51, InitBeanAndDestroyBean (com.xiaolyuh.init.destory)
invoke0:-1, NativeMethodAccessorImpl (sun.reflect)
invoke:62, NativeMethodAccessorImpl (sun.reflect)
invoke:43, DelegatingMethodAccessorImpl (sun.reflect)
invoke:498, Method (java.lang.reflect)
invoke:366, InitDestroyAnnotationBeanPostProcessor$LifecycleElement (org.springframework.beans.factory.annotation)
invokeInitMethods:311, InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata (org.springframework.beans.factory.annotation)
postProcessBeforeInitialization:134, InitDestroyAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
applyBeanPostProcessorsBeforeInitialization:409, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1626, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
源码:
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
// 执行初始化方法
metadata.invokeInitMethods(bean, beanName);
...
return bean;
}
// 执行@PostConstruct方法
public void invokeInitMethods(Object target, String beanName) throws Throwable {
Collection initMethodsToIterate =
(this.checkedInitMethods != null ? this.checkedInitMethods : this.initMethods);
if (!initMethodsToIterate.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (LifecycleElement element : initMethodsToIterate) {
// 通过反射调用@PostConstruct方法
element.invoke(target);
}
}
}
- 先通过
findLifecycleMetadata
方法找到被@PostConstruct
注解的元数据 - 通过反射调用
@PostConstruct
方法
invokeInitMethods() 执行自定义的初始化Bean方法
执行自定义的初始化Bean方法,执行顺序是afterPropertiesSet() -> @Bean 注解的 initMethod 方法。
调用链路:
invokeInitMethods:1673, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1630, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:555, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:202, AbstractBeanFactory (org.springframework.beans.factory.support)
invokeBeanFactoryPostProcessors:86, PostProcessorRegistrationDelegate (org.springframework.context.support)
invokeBeanFactoryPostProcessors:687, AbstractApplicationContext (org.springframework.context.support)
refresh:525, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
// 先判断是否实现了InitializingBean接口,如果是则调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction
- 先判断是否实现了InitializingBean接口,如果是则调用afterPropertiesSet方法
- 判断声明Bean时是否配置了initMethod方法,如果配置了则使用反射调用该方法
BeanPostProcessors.postProcessAfterInitialization() 后置处理器的后置方法执行
调用链路:
postProcessAfterInitialization:296, AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
applyBeanPostProcessorsAfterInitialization:423, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
initializeBean:1638, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:555, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:483, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
getObject:312, AbstractBeanFactory$1 (org.springframework.beans.factory.support)
getSingleton:230, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:308, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:197, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:761, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:867, AbstractApplicationContext (org.springframework.context.support)
refresh:543, AbstractApplicationContext (org.springframework.context.support)
:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
源码:
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 获取所有后置处理器,然后调用其postProcessAfterInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
- AnnotationAwareAspectJAutoProxyCreator:AOP代理的后置处理器,AOP生成代理的地方就是在后置处理器的postProcessAfterInitialization方法中实现的。