`
ex-huangshibao001
  • 浏览: 1081 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

spring框架加载完成后执行上下文刷新事件(ContextRefreshedEvent)

阅读更多

spring框架加载完成后执行上下文刷新事件(ContextRefreshedEvent)

目前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方法中完成开发所需的动作,代码如下所示:


 

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent>{
 protected Log logger = org.apache.commons.logging.LogFactory.getLog(getClass());
 List list = new ArrayList();
 @Override
 public void onApplicationEvent(ContextRefreshedEvent arg0) {
  // TODO Auto-generated method stub
  list.add("11");

  logger.error("StartupListener list : " +list.size() );
 }

}

 
分享到:
评论

相关推荐

    Spring源码学习四:BeanDefinition装载前奏曲1

    最后,`finishRefresh()`发布一个`ContextRefreshedEvent`,通知所有监听器Spring容器已经刷新完成。 总结来说,Spring的BeanDefinition装载过程涉及了从XML配置文件解析、BeanDefinition创建、BeanFactory初始化到...

    Spring监听资料

    在Spring框架中,监听器(Listeners)是一种关键的组件,它们允许我们对应用程序上下文(ApplicationContext)中的事件进行响应。Spring监听器是实现特定接口的类,这些接口提供了对Spring容器生命周期事件的处理...

    spring运行过程中动态注册bean

    `BeanFactoryAware`接口使得Bean可以被注入`BeanFactory`,而`ApplicationListener`接口则可以让Bean监听到应用上下文的刷新事件,从而在合适的时机执行动态注册逻辑。 ```java public class BeanFactoryAwareBean ...

    spring监听器共20页.pdf.zip

    Spring监听器是Spring框架中的一个重要组成部分,主要用于监听和响应应用上下文中的各种事件。在Spring应用中,监听器可以通过实现特定接口或者通过配置XML来定义,它们能够帮助开发者在应用程序的生命周期中执行...

    Spring Context内部知识:第1部分-刷新

    8. **广播初始化事件**:ApplicationContext在完成刷新后会发布一个ContextRefreshedEvent,任何监听这个事件的bean都可以在这个时刻进行相应的初始化工作。 9. **准备工厂状态**:此时,Spring Context已准备好...

    Spring教程之refresh()执行逻辑浅析

    在Spring框架中,`refresh()`方法是启动和更新Spring应用程序上下文的关键步骤。这个方法主要分为以下几个阶段: 1. **准备预处理(prepareRefresh())**: 在这一阶段,Spring容器会记录启动时间、标记容器为活动...

    如何在Spring Boot启动时运行定制的代码

    或者,实现`ApplicationListener`并监听`ContextRefreshedEvent`,这个事件在Spring上下文刷新后发布,即所有bean都已经创建和初始化。 ```java @Component class MyInitializer implements ...

    Spring IoC学习之ApplicationContext中refresh过程详解

    最后,`finishRefresh()` 完成刷新过程,通知生命周期处理器(`LifecycleProcessor`)容器已经刷新,并发布一个 `ContextRefreshedEvent` 事件,让其他监听者知道Spring容器已经准备就绪。 在异常处理部分,如果在...

    Spring创建Bean的过程

    ContextRefreshedEvent 在 ApplicationContext 初始化或刷新后发送的事件,ContextClosedEvent 在使用 ApplicationContext 的 close() 方法结束上下文的时候发送的事件,RequestHandledEvent 是一个与 web 相关的...

Global site tag (gtag.js) - Google Analytics