---
title: "spring框架加载完成后执行上下文刷新事件(ContextRefreshedEvent)"
author: "yangyongByJava"
date: "2012-07-19T14:04:31Z"
tags: []
categories: ["企业架构"]
slug: "spring-contextrefreshedevent"
draft: false
lastmod: "2015-05-29T16:54:44Z"
id: 1600581
url: "https://yangyongbyjava.iteye.com/blog/1600581"
---

目前spring框架是j2ee比较常用的项目开发技术，只需在web.xml文件中进行少许配置即可，代码如下所示：  
&lt;!--spring的配置文件--&gt;  
&lt;context-param&gt;  
&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;  
&lt;param-value&gt;classpath:config/applicationContext.xml&lt;/param-value&gt;  
&lt;/context-param&gt;  
&lt;!-- 启动spring容器的监听器--&gt;  
&lt;listener&gt;  
&lt;listenerclass&gt;  
                org.springframework.web.context.ContextLoaderListener  
        &lt;/listener-class&gt;  
&lt;/listener&gt;  
spring容器的许多初始化工作就是在ContextLoaderListener中完成，包括初始化applicationContext.xml文件中配置的bean对象、初始化国际化相关的对象(MessageSource)等，当这些步骤执行完后，最后一个就是执行刷新上下文事件，代码为  
public void refresh() throws BeansException, IllegalStateException {  
synchronized (this.startupShutdownMonitor) {  
try {  
                ...  
               ...  
               ...

// Initialize message source for this context.  
initMessageSource();  
                                 
                ...  
                ...  
                ...

// Last step: publish corresponding event.  
finishRefresh();  
} catch (BeansException ex) {  
// Destroy already created singletons to avoid dangling resources.  
destroyBeans();

// Reset 'active' flag.  
cancelRefresh(ex);

// Propagate exception to caller.  
throw ex;  
}  
}  
}

/\**  
\* Finish the refresh of this context, invoking the LifecycleProcessor's  
\* onRefresh() method and publishing the  
\* {@link org.springframework.context.event.ContextRefreshedEvent}.  
\*/  
protected void finishRefresh() {  
// Initialize lifecycle processor for this context.  
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.  
getLifecycleProcessor().onRefresh();

// Publish the final event.  
publishEvent(new ContextRefreshedEvent(this));  
}  
跟进finishRefresh方法可发现publishEvent(new ContextRefreshedEvent(this));这行代码，此处就是刷新上下文的事件。

public void publishEvent(ApplicationEvent event) {

Assert.notNull(event, "Event must not be null");

if (logger.isTraceEnabled()) {

logger.trace("Publishing event in " + getDisplayName() + ": " + event);

}

getApplicationEventMulticaster().multicastEvent(event);

if (this.parent != null) {

this.parent.publishEvent(event);

}

}

 

SimpleApplicationEventMulticaster.java

@SuppressWarnings("unchecked")

public void multicastEvent(final ApplicationEvent event) {

for (final ApplicationListener listener : getApplicationListeners(event)) {

Executor executor = getTaskExecutor();

if (executor != null) {

executor.execute(new Runnable() {

@SuppressWarnings("unchecked")

public void run() {

listener.onApplicationEvent(event);

}

});

}

else {

listener.onApplicationEvent(event);

}

}

}

开发者可自己定义一个监听器让其实现ApplicationListener接口，覆盖onApplicationEvent方法，在onApplicationEvent方法中完成开发所需的动作，代码如下所示：

@Component  
public class SpringContextListener implements ApplicationListener {

public void onApplicationEvent(ApplicationEvent event) {  
if(event instanceof ContextRefreshedEvent) { //spring容器启动完成  
...  
                ...  
                ...  
}  
}  
}