目前spring框架是j2ee比较常用的项目开发技术,只需在web.xml文件中进行少许配置即可,代码如下所示:
<!--spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<!-- 启动spring容器的监听器-->
<listener>
<listenerclass>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
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容器启动完成
...
...
...
}
}
}