阅读本文之前,请先阅读上篇博文Spring Bean后置处理器(BeanPostProcessor及其子接口)源码分析,本文将不再介绍BeanPostProcessor相关内容。
既然源码分析,我就直奔主题了。首先是org.springframework.context.support.AbstractApplicationContext.refresh()的源码:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//准备Refresh上下文环境,比如设置当前环境active=true,初始化及校验PropertySources
prepareRefresh();
// 刷新并获取bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备bean工厂以供当前上下文中使用
prepareBeanFactory(beanFactory);
try {
// 允许在上下文子类中对bean工厂进行后置处理
postProcessBeanFactory(beanFactory);
// 调用上下文中注册为bean的工厂后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// 注册Bean后置处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// 初始化特定上下文子类中的其他特殊bean
onRefresh();
// 注册监听器
registerListeners();
// 实例化所有剩余的(非延迟初始化)单例.
finishBeanFactoryInitialization(beanFactory);
// 发布相应事件,完成刷新
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 发生异常,则销毁已经实例化的bean
destroyBeans();
// Reset 'active' flag.
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();
}
}
}
接下来是生命周期执行顺序测试代码:
测试Bean代码(该Bean与NewsService循环依赖,为了执行循环依赖后置处理器)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("dependencyService")
public class DependencyService implements InitializingBean, DisposableBean,BeanNameAware,BeanFactoryAware {
private static final Logger _LOG = LoggerFactory.getLogger(DependencyService.class);
@Autowired
NewsServiceImpl newsServiceImpl;
public DependencyService() {