Spring中的事件处理

ApplicationContext 是Spring的核心模块,管理着Beans完整的生命周期。当加载Bean时,ApplicationContext会发布特定类型的事件。

eg:当Context启动时ContextStartEvent被发布,当关闭时,ContextStoppedEvent被发布。

ApplicationContext事件处理被ApplicationEvent类和ApplicationListener接口提供。因此,实现了ApplicationListener的bean,每次ApplicationContext发布ApplicationEvent时,Bean将会被通知。

Spring内建事件

  • ContextRefreshedEvent : 当ApplicationContext被初始化或者刷新时被发布。也可以通过调用ConfigurableApplicationContext接口的refresh()函数发起。
  • ContextStartedEvent : 当Application使用ConfigurableApplicationContext的start()方法启动时被发布。您可以轮询您的数据库,也可以在收到此事件后重新启动任何已停止的应用程序。
  • ContextStoppedEvent : 当ApplicationContext在ConfigurableApplicationContext接口上使用stop()方法停止时,就会发布这个事件。你可以在收到这个活动后做家务。
  • ContextClosedEvent : 当使用ConfigurableApplicationContext接口上的close()方法关闭ApplicationContext时,将发布此事件。一个封闭的环境到达了生命的终点;不能刷新或重新启动。
  • RequestHandledEvent : 这是一个特定于web的事件,它告诉所有bean HTTP请求已经得到了服务。

Spring的事件处理是单线程的,因此如果发布了一个事件,直到并且除非所有接收者都得到消息,否则进程将被阻塞,线程将不会继续。因此,如果要使用事件处理,那么在设计应用程序时应该小心。

监听Context事件

要想监听一个context事件,bean需要实现仅有一个方法onApplicationEvent()的ApplicationListener接口

Example

HelloWorld.java

public class HelloWorld {
private String message; public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

CStartEventHandler.java

public class CStartEventHandler
implements ApplicationListener<ContextStartedEvent>{ public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent Received");
}
}

CStopEventHandler

public class CStopEventHandler
implements ApplicationListener<ContextStoppedEvent>{ public void onApplicationEvent(ContextStoppedEvent event) {
System.out.println("ContextStoppedEvent Received");
}
}

MainApp.java

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();
}
}

Beans

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <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"/> </beans>

输出:

ContextStartedEvent Received
Your Message : Hello World!
ContextStoppedEvent Received

自定义Spring事件

下边的案例将讲述如何编写和发布你自己的自定义事件

添加自定义事件CustomEvent.java,继承ApplicationEvent类

public class CustomEvent extends ApplicationEvent{
public CustomEvent(Object source) {
super(source);
}
public String toString(){
return "My Custom Event";
}
}

添加自定义事件发布类CustomEventPublisher.java,实现ApplicationEventPublisherAware接口

public class CustomEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher; public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish() {
CustomEvent ce = new CustomEvent(this);
publisher.publishEvent(ce);
}
}

自定义事件监听处理类,实现ApplicationListener

public class CustomEventHandler implements ApplicationListener<CustomEvent> {
public void onApplicationEvent(CustomEvent event) {
System.out.println(event.toString());
}
}

MainApp.java

public class MainApp {
public static void main(String[] args) {
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml"); CustomEventPublisher cvp =
(CustomEventPublisher) context.getBean("customEventPublisher"); cvp.publish();
cvp.publish();
}
}

Beans.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id = "customEventHandler" class = "com.tutorialspoint.CustomEventHandler"/>
<bean id = "customEventPublisher" class = "com.tutorialspoint.CustomEventPublisher"/> </beans>

注意不要忘记添加customEventHandler,虽然在主函数中没有直接使用,但是context需要检查实现了ApplicationListener的

bean,所以需要在xml文件中,添加该bean。

输出:

my Custom Event
my Custom Event

Spring入门学习笔记(3)——事件处理类的更多相关文章

  1. Spring入门学习笔记(1)

    目录 Spring好处 依赖注入 面向面编程(AOP) Spring Framework Core Container Web Miscellaneous 编写第一个程序 IoC容器 Spring B ...

  2. [Spring入门学习笔记][静态资源]

    遗留问题 在上一节课的作业中,我们一定遇到了一点问题——虽然将页面内容正确的返回给了浏览器,但是浏览器显示的样式却是不正确的,这是因为在HTML的\标签中我们这样引入了CSS资源: <link ...

  3. [Spring入门学习笔记][创建网站URL]

    设计网站的URL 现代的Web站点都会设计一套拥有明确意义,方便用户记忆的URL,不论是域名还是路径,以天码营为例: http://tianmaying.com/courses表示网站下所有的课程列表 ...

  4. [spring入门学习笔记][spring的IoC原理]

    什么叫IoC 控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度.其中最常见的方式叫做依赖注入(Dependency ...

  5. [Spring入门学习笔记][Spring的AOP原理]

    AOP是什么? 面向切面编程 软件工程有一个基本原则叫做“关注点分离”(Concern Separation),通俗的理解就是不同的问题交给不同的部分去解决,每部分专注于解决自己的问题.这年头互联网也 ...

  6. [Spring入门学习笔记][Spring Boot]

    什么是Spring Boot Spring Boot正是在这样的一个背景下被抽象出来的开发框架,它本身并不提供Spring框架的核心特性以及扩展功能,只是用于快速.敏捷地开发新一代基于Spring框架 ...

  7. java入门学习笔记之1(类的定义,代码的编译执行)

    这篇文章讲解Java代码的基本执行过程 我们先抛开各种JAVA IDE,开发工具,只使用文本编辑器,以突出最本质的东西. 在Linux环境下,我们编辑一个文件: vim HelloWorld.java ...

  8. Spring入门学习笔记(4)——JDBC的使用

    目录 Spring JDBC框架概览 JdbcTemplate类 配置数据源 数据访问对象(Data Access Object,DAO) 执行SQL命令 Spring JDBC框架概览 使用传统的J ...

  9. Spring入门学习笔记(2)——基于Java的配置

    目录 基于Java的配置 @Configuration & @Bean Annotations Example 注入Bean依赖 @Import注解 Lifecycle Callbacks(声 ...

随机推荐

  1. hadoop学习;hdfs操作;执行抛出权限异常: Permission denied;api查看源代码方法;源代码不停的向里循环;抽象类通过debug查找源代码

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010026901/article/details/26587251 eclipse快捷键alt+s ...

  2. 【洛谷】【二分答案+贪心】P1316 丢瓶盖

    [题目描述:] 陶陶是个贪玩的孩子,他在地上丢了A个瓶盖,为了简化问题,我们可以当作这A个瓶盖丢在一条直线上,现在他想从这些瓶盖里找出B个,使得距离最近的2个距离最大,他想知道,最大可以到多少呢? [ ...

  3. 【洛谷】【堆】P1801 黑匣子_NOI导刊2010提高(06)

    [题目描述:] Black Box是一种原始的数据库.它可以储存一个整数数组,还有一个特别的变量i.最开始的时候Black Box是空的.而i等于0.这个Black Box要处理一串命令. 命令只有两 ...

  4. Hive学习之路 (十六)Hive分析窗口函数(四) LAG、LEAD、FIRST_VALUE和LAST_VALUE

    数据准备 数据格式 cookie4.txt cookie1, ::,url2 cookie1, ::,url1 cookie1, ::,1url3 cookie1, ::,url6 cookie1, ...

  5. Hadoop学习之路(十六)Hadoop命令hadoop fs -ls详解

    http://blog.csdn.net/strongyoung88/article/details/68952248

  6. lvm xfs 扩容

    lvresize -L 300M /dev/vg1/lv1 #重新设定大小 e2fsck -f /dev/vg1/lv1 #检查磁盘错误 (针对ext4执行) resize2fs /dev/vg1/l ...

  7. C++ - 类的虚函数\虚继承所占的空间

    类的虚函数\虚继承所占的空间 本文地址: http://blog.csdn.net/caroline_wendy/article/details/24236469 char占用一个字节, 但不满足4的 ...

  8. 第一章 Linux内核简介

    1. 操作系统和内核 操作系统是指在整个系统中负责完成最基本功能和系统管理的那些部分.包括内核.设备驱动程序.启动引导程序.命令行shell或者其他种类的用户界面.基本的文件管理工具和系统工具. 用户 ...

  9. H5 开发中常见的小问题

    1.解决 浏览器 返回按钮不刷新的问题 window.onpageshow = function(event) { if (event.persisted) { window.location.rel ...

  10. 探索photo-sphere-viewer全景插件

    此插件是一位外国人写的,官网API地址:https://photo-sphere-viewer.js.org/#methods 我只是记录下我在使用此插件时用到的方法和相关属性,以防以后忘记 1.按要 ...