IOC-Bean的生命周期
- bean的生命周期
抛开初始化beanFactory等前面的加载过程,单看bean的生命周期,直接进入/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java的594行,doCreate()方法中,找到initializeBean初始化bean instance,这也就是bean生命周期的开始.
点进去查看此方法,重点关注几个重要方法就能明白流程
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
//进入该invokeAwareMethods方法可以看到setBeanName,setClassLoader,setBeanFactory方法
//重要
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//重要
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//重要
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()) {
//重要
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
-
在BeanNameAware中的setBeanName设置bean的名称
-
在BeanClassLoaderAware中设置bean的类加载器setBeanClassLoader,回调,提供给bean的实例
-
在BeanFactoryAware中,设置setBeanFactory,并且回调,提供给bean的实例
-
调用后置处理器 BeanPostProcessor 初始化前方法
-
唤醒初始化方法invokeInitMethods(其中包括调用InitializingBean对象的afterPropertiesSet方法,和invokeCustomInitMethod调用自定义初始化方法)
-
调用后置处理器 BeanPostProcessor 初始化后方法
-
bean就可以使用了!
-
容器关闭,bean销毁,调用DisposableBean的destroy方法. 回到doGet()方法 ,在创建bean的收就已经注册了 可抛弃属性registerDisposableBeanIfNecessary
参考图片: