Spring 中的事件处理

Spring 中的事件处理

你已经看到了在全部章节中 Spring 的核心是 ApplicationContext,它负责管理 beans 的完整生命周期。当加载 beans 时,ApplicationContext 发布某些类型的事件。例如,当上下文启动时,ContextStartedEvent 发布,当上下文中止时,ContextStoppedEvent 发布。html

经过 ApplicationEvent 类和 ApplicationListener 接口来提供在 ApplicationContext 中处理事件。若是一个 bean 实现 ApplicationListener,那么每次 ApplicationEvent 被发布到 ApplicationContext 上,那个 bean 会被通知。web

序号spring

Spring 内置事件 & 描述数据库

1spa

ContextRefreshedEvent线程

ApplicationContext 被初始化或刷新时,该事件被发布。这也能够在 ConfigurableApplicationContext 接口中使用 refresh() 方法来发生。设计

2code

ContextStartedEventxml

当使用 ConfigurableApplicationContext 接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你能够调查你的数据库,或者你能够在接受到这个事件后重启任何中止的应用程序。htm

3

ContextStoppedEvent

当使用 ConfigurableApplicationContext 接口中的 stop() 方法中止 ApplicationContext 时,发布这个事件。你能够在接受到这个事件后作必要的清理的工做。

4

ContextClosedEvent

当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。

5

RequestHandledEvent

这是一个 web-specific 事件,告诉全部 bean HTTP 请求已经被服务。

因为 Spring 的事件处理是单线程的,因此若是一个事件被发布,直至而且除非全部的接收者获得的该消息,该进程被阻塞而且流程将不会继续。所以,若是事件处理被使用,在设计应用程序时应注意。

监听上下文事件

为了监听上下文事件,一个 bean 应该实现只有一个方法 onApplicationEvent() 的 ApplicationListener 接口。所以,咱们写一个例子来看看事件是如何传播的,以及如何能够用代码来执行基于某些事件所需的任务。

让咱们在恰当的位置使用 Eclipse IDE,而后按照下面的步骤来建立一个 Spring 应用程序:

public class CStartEventHandler 
   implements ApplicationListener<ContextStartedEvent>{
   //容器启动事件
   public void onApplicationEvent(ContextStartedEvent event) {
      System.out.println("ContextStartedEvent Received");
   }
}

 

public class CStopEventHandler 
   implements ApplicationListener<ContextStoppedEvent>{
   public void onApplicationEvent(ContextStoppedEvent event) {
      System.out.println("ContextStoppedEvent Received");
   }
}
public class MainApp {
   public static void main(String[] args) {
      ConfigurableApplicationContext context = 
      new ClassPathXmlApplicationContext("Beans.xml");

      // Let us raise a start event.
      context.start();

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();

      // Let us raise a stop event.
      context.stop();
   }
}

 

<bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
      <property name="message" value="Hello World!"/>
   </bean>

   <bean id="cStartEventHandler" 
         class="com.tutorialspoint.CStartEventHandler"/>

   <bean id="cStopEventHandler" 
         class="com.tutorialspoint.CStopEventHandler"/>

 

自定义事件

相关文章
相关标签/搜索