publicvoidrefresh()throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 准备刷新的上下文环境 prepareRefresh(); // 1
// Tell the subclass to refresh the internal bean factory. // 初始化 BeanFactory,并进行 XML 文件读取 ConfigurableListableBeanFactorybeanFactory= obtainFreshBeanFactory(); // 2
// Prepare the bean factory for use in this context. // 对 BeanFactory 进行各种功能填充 prepareBeanFactory(beanFactory); // 3
try { // Allows post-processing of the bean factory in context subclasses. // 子类覆盖方法做额外的处理 postProcessBeanFactory(beanFactory); // 4
// Invoke factory processors registered as beans in the context. // 激活各种 BeanFactory 处理器 invokeBeanFactoryPostProcessors(beanFactory); // 5
// Destroy already created singletons to avoid dangling resources. 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(); } } }
初始化前的准备工作,例如对系统属性或者环境变量进行准备及验证。
在某种情况下项目的使用需要读取某些系统变量,而这个变量的设置很可能会影响着系统的正确性,那么ClassPathXmlApplicationContext为我们提供的这个准备函数就显得非常必要,它可以在 Spring 启动的时候提前对必须的变量进行存在性验证。
if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); }
// Initialize any placeholder property sources in the context environment // 留给子类覆盖 initPropertySources();
// Validate that all properties marked as required are resolvable // see ConfigurablePropertyResolver#setRequiredProperties // 验证需要的属性文件是否都已经放入环境中 getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = newLinkedHashSet<ApplicationEvent>(); }
initPropertySources 正符合 Spring 的开放式结构设计,给用户最大扩展 Spring 的能力。用户可以根据自身的需要重写 initPropertySources 方法,并在方法中进行个性化的属性处理及设置。
protectedvoidloadBeanDefinitions(DefaultListableBeanFactory beanFactory)throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. // 为指定的 BeanFactory 创建 XmlBeanDefinitionReader XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's // resource loading environment. // 对 beanDefinitionReader 进行环境变量的设置 beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. // 对 BeanDefinitionReader 进行设置,可以覆盖 initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }
protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. // 设置 beanFactory 的 classLoader 为当前 context 的 classLoader beanFactory.setBeanClassLoader(getClassLoader()); // 设置 beanFactory 的表达式语言处理器,默认可使用 #{bean.xxx} 的形式来调用相关属性值 beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 为beanFactory 增加了一个默认的 propertyEditor,这个主要是对 bean 的属性等设置管理的一个工具 beanFactory.addPropertyEditorRegistrar(newResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks. // 添加 BeanPostProcessor beanFactory.addBeanPostProcessor(newApplicationContextAwareProcessor(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 interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // 设置了几个自动装配的特殊规则 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners. // 4.3.4 后添加的 // 避免 BeanPostProcessor 被 getBeanNamesForType 调用 beanFactory.addBeanPostProcessor(newApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found. // 增加对 AspectJ 的支持 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// Register default environment beans. // 添加默认的系统环境 bean if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }