注意:以下基于Spring 5.1.8版本
Spring容器的启动
public class BeanFactoryTest{
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/beanFactoryTest.xml");
MyTestBean user = (MyTestBean) applicationContext.getBean("myTestBean");
}
}
源码分析
先来看看这行代码都做了哪些事情。
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/beanFactoryTest.xml");
ClassPathXmlApplicationContext
调用ClassPathXmlApplicationContext的构造方法,入参是配置文件的地址。
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}
ClassPathXmlApplicationContext是一个XML应用上下文,从类路径获取上下文定义文件。再接着调用本类的另一个构造方法,传入的refresh参数为true,表示要调用AbstractApplicationContext的refresh()方法自动刷新上下文。
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
super(parent);
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
AbstractApplicationContext > refresh()
refresh()方法是用来加载所有的Bean定义和创建所有的单例。
(1)startupShutdownMonitor是启动关闭监控标识,是用来同步应用上下文(context)刷新(refresh)和销毁(destroy)操作。
(2)调用本类的prepareRefresh()方法做刷新上下文的准备。
(3)告诉子类刷新内部bean工厂,准备在上下文使用的Bean工厂。
(4)允许在上下文子类中对bean工厂进行后处理。
(5)调用在上下文中注册为bean的工厂处理器。
(6)注册bean处理器用来拦截bean的创建。
(7)为此上下文初始化消息源。
(8)为此上下文初始化事件多播器。
(9)在特定上下文子类中初始化其他特殊bean。
(10)检查监听器bean并注册它们。
(11)实例化所有剩余的(非延迟初始化)单例。
(12)最后一步:发布相应的事件。
(13)如果以上过程出现异常,就销毁已创建的单例以避免资源悬空。将active标识设置为false,将异常向上抛出。
(14)无论是否出现异常,最后重置Spring核心中的常见自省缓存,因为我们可能不再需要单例bean的元数据。
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
AbstractApplicationContext > prepareRefresh()
(1)startupDate是用来记录上下文启动的系统时间。
(2)将上下文是否关闭的标识设置为false。将上下文是否活跃的标识设置为true。(3)this.initPropertySources()用来初始化上下文环境的所有占位符属性源。(4)this.getEnvironment().validateRequiredProperties()会初始化environment属性,验证所有标记为必需的属性都是可解析的。
(5)earlyApplicationListeners是刷新之前就会注册的本地监听器Set集合,applicationListeners是静态指定的监听器Set集合,当earlyApplicationListeners为空时,会初始化内容是applicationListeners;当earlyApplicationListeners不为空时,会将applicationListeners清空,内容再重置为earlyApplicationListeners。
(6)最后再初始化earlyApplicationEvents属性,earlyApplicationEvents是在多播器设置之前发布的应用程序事件。
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (this.logger.isDebugEnabled()) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Refreshing " + this);
} else {
this.logger.debug("Refreshing " + this.getDisplayName());
}
}
this.initPropertySources();
this.getEnvironment().validateRequiredProperties();
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
} else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
this.earlyApplicationEvents = new LinkedHashSet();
}
AbstractApplicationContext > obtainFreshBeanFactory()
调用本类的refreshBeanFactory()方法判断是否存在bean工厂,如果存在就进行销毁;再重新实例化一个bean工厂。再调用AbstractRefreshableApplicationContext的getBeanFactory()方法获取在refresh()创建的bean工厂,如果获取到的bean工厂是空,会抛出异常。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
AbstractApplicationContext > prepareBeanFactory()
配置bean工厂的标准上下文特征。
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.setBeanClassLoader(this.getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
if (beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
if (!beanFactory.containsLocalBean("environment")) {
beanFactory.registerSingleton("environment", this.getEnvironment());
}
if (!beanFactory.containsLocalBean("systemProperties")) {
beanFactory.registerSingleton("systemProperties", this.getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean("systemEnvironment")) {
beanFactory.registerSingleton("systemEnvironment", this.getEnvironment().getSystemEnvironment());
}
}
AbstractApplicationContext > postProcessBeanFactory()
postProcessBeanFactory()方法在AbstractApplicationContext是个空方法,子类可以覆写这个方法。用于标准初始化后,修改应用程序上下文的内部bean工厂。 所有bean定义都将被加载,但尚未实例化任何bean。 这允许在某些ApplicationContext实现中注册特殊的BeanPostProcessor等。
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
AbstractApplicationContext > invokeBeanFactoryPostProcessors()
实例化并调用所有注册的BeanFactoryPostProcessor Bean,并遵循显式顺序(如果给定的话)。必须在单例实例化之前调用。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver")) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
AbstractApplicationContext > registerBeanPostProcessors()
实例化并注册所有BeanPostProcessor Bean,并遵循显式顺序(如果有的话)。必须在应用程序Bean的任何实例化之前调用。
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
AbstractApplicationContext > initMessageSource()
判断bean工厂是否存在MessageResource:
(1)如果存在,获取,再判断是否有父MessageSource,如果没有,就把父上下文设置为父MessageSource;
(2)如果不存在,实例化一个空MessageSource以接受getMessage的调用,并设置父MessageSource为父上下文;
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("messageSource")) {
this.messageSource = (MessageSource)beanFactory.getBean("messageSource", MessageSource.class);
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource)this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(this.getInternalParentMessageSource());
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Using MessageSource [" + this.messageSource + "]");
}
} else {
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(this.getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton("messageSource", this.messageSource);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Unable to locate MessageSource with name 'messageSource': using default [" + this.messageSource + "]");
}
}
}
AbstractApplicationContext > initApplicationEventMulticaster()
初始化ApplicationEventMulticaster。如果上下文中未定义,则使用SimpleApplicationEventMulticaster。
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (beanFactory.containsLocalBean("applicationEventMulticaster")) {
this.applicationEventMulticaster = (ApplicationEventMulticaster)beanFactory.getBean("applicationEventMulticaster", ApplicationEventMulticaster.class);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
} else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton("applicationEventMulticaster", this.applicationEventMulticaster);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [" + this.applicationEventMulticaster + "]");
}
}
}
AbstractApplicationContext > refresh()
可以被覆盖的模板方法,用来添加上下文指定的刷新工作。在单例的实例化之前,被特殊bean的实例化调用。
protected void onRefresh() throws BeansException {
}
AbstractApplicationContext > registerListeners()
首先注册静态指定的监听器。在这里不初始化FactoryBeans,保留所有常规bean,以使后处理器适用于它们。用个多播器发布早期的应用程序事件。
protected void registerListeners() {
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
AbstractApplicationContext > finishBeanFactoryInitialization()
完成此上下文的Bean工厂的初始化,初始化所有剩下的单例实例。
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
//初始化ConversionService实例
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
//如果没有bean后处理器,则注册默认的嵌入式值解析器,例如PropertyPlaceholderConfigurer
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
//尽早初始化LoadTimeWeaverAware Bean,以便尽早注册其转换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
//停止使用临时ClassLoader进行类型匹配。
beanFactory.setTempClassLoader(null);
//允许缓存所有bean定义元数据.
beanFactory.freezeConfiguration();
//实例化所有剩余的(非延迟初始化)单例。
beanFactory.preInstantiateSingletons();
}
AbstractApplicationContext > finishRefresh()
完成上下文的刷新,调用LifecycleProcessor的onRefresh()方法并发布org.springframework.context.event.ContextRefreshedEvent
protected void finishRefresh() {
//清除上下文级别的资源缓存(例如来自扫描的ASM元数据)。
this.clearResourceCaches();
//为此上下文初始化生命周期处理器。
this.initLifecycleProcessor();
//将刷新传播到生命周期处理器。
this.getLifecycleProcessor().onRefresh();
this.publishEvent((ApplicationEvent)(new ContextRefreshedEvent(this)));
LiveBeansView.registerApplicationContext(this);
}
参考资料
《Spring源码深度分析》
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。