目录
2、BeanPostProcessor的postProcessBeforeInitialization方法回调
3、ApplicationContextAwareProcessor的postProcessBeforeInitialization
4、InitializingBean的afterPropertiesSet回调;自定义init方法回调
1)、回调InitializingBean的afterPropertiesSet方法
5、BeanPostProcessor的postProcessAfterInitialization方法回调
initializeBean方法就是Bean的生命周期过程,可以参照Spring-Bean的作用域和生命周期。从下面的步骤可以大致分为4步骤进行回调。
protected Object initializeBean(final String beanName, final Object bean,
@Nullable RootBeanDefinition mbd) {
// 回调Bean实现的Aware相关接口
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
// 回调BeanPostProcessor的before接口
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
// 回调init接口
invokeInitMethods(beanName, wrappedBean, mbd);
// 回调BeanPostProcessor的after接口
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
1、Aware接口回调
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) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
- 如果Bean实现了BeanNameAware接口,则在此处回调setBeanName方法
- 如果Bean实现了BeanClassLoaderAware接口,则在此处回调setBeanClassLoader方法
- 如果实现了BeanFactoryAware接口,则在此处回调setBeanFactory方法
2、BeanPostProcessor的postProcessBeforeInitialization方法回调
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
// 如果前置回调方法中修改了Bean,则返回修改后的Bean
if (current == null) {
return result;
}
result = current;
}
return result;
}
遍历所有的BeanPostProcessor,回调postProcessBeforeInitialization前置方法,该方法中允许对Bean进行修改。其中有个比较特殊的ApplicationContextAwareProcessor,并且为列表的第一个被回调。
3、ApplicationContextAwareProcessor的postProcessBeforeInitialization
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;
}
// 省略权限检查部分的代码
invokeAwareInterfaces(bean);
return bean;
}
如果Bean没有实现以上接口则直接返回,否则就进行回调:
private void invokeAwareInterfaces(Object bean) {
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);
}
}
- 如果Bean实现了EnvironmentAware接口,则在此处回调setEnvironment方法
- 如果Bean实现了EmbeddedValueResolverAware接口,则在此处回调setEmbeddedValueResolver方法
- 如果实现了ResourceLoaderAware接口,则在此处回调setResourceLoader方法
- 如果实现了ApplicationEventPublisherAware接口,则在此处回调setApplicationEventPublisher方法
- 如果实现了MessageSourceAware接口,则在此处回调setMessageSource方法
- 如果实现了ApplicationContextAware接口,则在此处回调setApplicationContext方法
4、InitializingBean的afterPropertiesSet回调;自定义init方法回调
protected void invokeInitMethods(String beanName, final Object bean,
@Nullable RootBeanDefinition mbd) throws Throwable {
// 回调InitializingBean的afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
// 省略部分代码
((InitializingBean) bean).afterPropertiesSet();
}
// 回调自定义的init方法
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
1)、回调InitializingBean的afterPropertiesSet方法
如果Bean实现了InitializingBean接口,则在此处回调afterPropertiesSet方法。
2)、自定义init方法回调
如果Spring xml配置中的<bean />标签设置了init-method属性,或者在Bean的方法上添加@PostConstruct注解,则在该出回调自定义的初始化方法。解析完成后定义的方法名称被存储为BeanDefinition的initMethodName字段中。回调过程如下:
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
// 获取自定义名称,不能为空
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
// 根据方法是否为Public,获取反射的Method
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
// 检查是否一定要进行回调
if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else {
// Ignore non-existent default lifecycle methods.
return;
}
}
// 当前定义的可能只是接口,则获取真是的方法
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
// 如果是非public则强制破解,反射回调方法
ReflectionUtils.makeAccessible(methodToInvoke);
methodToInvoke.invoke(bean);
}
5、BeanPostProcessor的postProcessAfterInitialization方法回调
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
历所有的BeanPostProcessor,回调postProcessAfterInitialization后置方法,这也是Aop实现的根本。现在拿到的Bean是已经不需要再进行修改的了,则在该出根据对象本身,创建代理对象,返回代理对象,进行使用。
在最外层,会将实现了DisposableBean的以适配器添加到销毁容器中,到时候进行回调。就完成了Bean的整个生命周期。
总结Bean的生命周期
1、BeanNameAware#setBeanName方法
2、BeanClassLoaderAware#setBeanClassLoader方法
3、BeanFactoryAware#setBeanFactory方法
4、EnvironmentAware#setEnvironment方法
5、EmbeddedValueResolverAware#setEmbeddedValueResolver方法
6、ResourceLoaderAware#setResourceLoader方法
7、ApplicationEventPublisherAware#setApplicationEventPublisher方法
8、MessageSourceAware#setMessageSource方法
9、ApplicationContextAware#setApplicationContext方法
10、其他BeanPostProcess#postProcessBeforeInitialization方法
11、InitializingBean#afterPropertiesSet方法
12、init-method或者@PostConstruct定义的方法
13、BeanPostProcess#postProcessAfterInitialization方法
14、正常Bean使用阶段
15、注册DisposableBean#destroy方法的回调