上一篇讲解了Spring的ContextLoader类在初始化Spring应用上下文时,调用了refresh()方法,该方法的具体实现就在AbstractApplicationContext类里
下面就来看一下refresh方法都做了哪些事:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// 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();
}
}
}
其一执行prepareRefresh()
方法,顾名思义就是为刷新做准备的!
/**
1. Prepare this context for refreshing, setting its startup date and
2. active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
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 = new LinkedHashSet<ApplicationEvent>();
}
this.startupDate = System.currentTimeMillis();
设置context的启动时间。this.closed.set(false);
设置context的关闭标识为false。this.active.set(true);
设置context的活动标识为true。initPropertySources();
初始化context environment(上下文环境)中的占位符属性来源。getEnvironment().validateRequiredProperties();
验证所有标记为“必需”的属性是否可解析this.earlyApplicationEvents = new LinkedHashSet();
spring event发布及监听实例执行prepareRefresh()
方法,控制台会打印如下日志:
[2019-01-03 16:49:48 INFO org.springframework.web.context.support.XmlWebApplicationContext:583] Refreshing Root WebApplicationContext: startup date [Thu Jan 03 16:49:40 CST 2019]; root of context hierarchy
其二执行ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
让AbstractApplicationContext的子类刷新内部bean工厂(实际上就是重新创建一个bean工厂)
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
其中refreshBeanFactory()
方法调用的是AbstractRefreshableApplicationContext类的refreshBeanFactory()方法,从上一篇的类关系图,我们知道AbstractRefreshableApplicationContext类是AbstractApplicationContext类的子类
AbstractRefreshableApplicationContext的refreshBeanFactory()
方法:
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
该方法的逻辑从上至下就是,初始化一个新的BeanFactory,并加载定义的Bean至BeanFactory,(讲解这一系列文章使用的Spring mvc项目,spring的版本是4.3.11)因为是Spring mvc项目,所以bean的定义都是在xml里配置的,类似这样:
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
既然要加载Bean到BeanFactory,则会把xml都过遍历解析一遍,那都解析哪些xml呢?
如果跟进代码,刚会发现loadBeanDefinitions方法调用的是XmlWebApplicationContext类的loadBeanDefinitions方法:
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
其中再跟进loadBeanDefinitions()
方法源码:
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
String[] configLocations = getConfigLocations();
if (configLocations != null) {
for (String configLocation : configLocations) {
reader.loadBeanDefinitions(configLocation);
}
}
}
这里的getConfigLocations()
方法获取的就是父类AbstractRefreshableConfigApplicationContext的configLocations变量,
上一篇讲到了contextConfigLocation的配置(在web.xml里配置),还讲到了配置的value值被set到AbstractRefreshableConfigApplicationContext类的configLocations变量里, 这不就对上了吗!!!
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring/*.xml
这里配置了工程需要加载的xml文件的位置, 这些xml文件是通过上面loadBeanDefinitions
方法的for循环进行一一加载解析,初始化Bean的,并将Bean实例放在BeanFactory里,BeanFactory最后交给Context管理!
执行loadBeanDefinitions(XmlBeanDefinitionReader reader)
方法会输入如下日志(结合日志分析源更清楚):
[2019-01-09 15:10:52 INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader:317] Loading XML bean definitions from file [D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\accplatform-job\WEB-INF\classes\spring\applicationContext-msg.xml]
[2019-01-09 15:10:57 INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader:317] Loading XML bean definitions from file [D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\accplatform-job\WEB-INF\classes\spring\applicationContext-redis.xml]
[2019-01-09 15:10:57 INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader:317] Loading XML bean definitions from file [D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\accplatform-job\WEB-INF\classes\spring\applicationContext.xml]
其三refresh()中执行prepareBeanFactory(beanFactory);
方法,为了下面在Spring上下文中使用BeanFactory做准备,查看其源码:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
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 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.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
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());
}
}
从源码可以看出,该方法基本在初始化BeanFactory的数据,也称为BeanFactory的配置化(Configure)过程
BeanFctory属于Spring IOC里的重点类(有点复杂), 后面要从Spring IOC的角度来全面解析一下Spring的Bean工场系列类,现在是从Spring Context的角度来解析的,所以先简单带过…
其四refresh()中执行postProcessBeanFactory(beanFactory);
其实执行的是AbstractRefreshableWebApplicationContext类的方法:
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
这里重点是下面的两行代码,注册Web特定的作用域(“request”, “session”, “globalSession”, “application”)至BeanFactory中,方便WebApplicationContext使用,作用域这里可以先这样理解(从Bean的创建角度来理解):
其五refresh()中执行invokeBeanFactoryPostProcessors(beanFactory);
其源码为:
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
从源码注释可以看出,该方法的调用必须在所有的singleton实例化之前,而且从该方法的名称可以看出来,引入了IOC的Processor角色(其实就是Bean工厂里的处理器),Bean的处理器下面做了大量复杂的工作, 具体都做了什么工作,Context篇系统这里先不深入解析…
其六refresh()中执行registerBeanPostProcessors(beanFactory);
其源码为:
/**
* Instantiate and invoke all registered BeanPostProcessor beans,
* respecting explicit order if given.
* Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
还是对BeanFactory的处理!!! refresh()方法从其二至其六都是关于BeanFactory的处理…
下篇接着解析AbstractApplicationContext的refresh()
…