文章目录

Spring中的事件处理

Spring 的核心是 ApplicationContext,它负责管理 beans 的完整生命周期。当加载 beans 时,ApplicationContext 发布某些类型的事件。例如,当上下文启动时,ContextStartedEvent 发布,当上下文停止ContextStoppedEvent发布。

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

Spring 提供了以下的标准事件:

序号 Spring 内置事件 & 描述
1 ContextRefreshedEvent*ApplicationContext 被初始化或刷新时,该事件被发布。这也可以在 ConfigurableApplicationContext*接口中使用 refresh() 方法来发生。
2 ContextStartedEvent当使用 ConfigurableApplicationContext 接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
3 ContextStoppedEvent当使用 ConfigurableApplicationContext 接口中的 stop() 方法停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
4 ContextClosedEvent当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。
5 RequestHandledEvent这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。

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

监听上下文事件

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

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

步骤 描述
1 创建一个名称为 SpringEventTest 的项目,并且在创建项目的 src 文件夹中创建一个包com.szxy
2 使用 Add External JARs 选项,添加所需的 Spring 库
3 com.szxy包中创建 Java 类 HelloSpringEventCStartEventHandlerCStopEventHandler* 和 Start
4 src 文件夹中创建 Bean 的配置文件 applicationContext.xml.xml
5 最后一步是创建的所有 Java 文件和 Bean 配置文件的内容,并运行应用程序,解释如下所示.

这里是 HelloSpringEvent.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.szxy;

public class HelloSpringEvent {

	private String msg;

	public HelloSpringEvent(){
System.out.println("HelloSpringEvent 初始化");
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} }

下面是 CStartEventHandler.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.szxy;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent; /**
* ContextStartedEvent:
* 当使用 ConfigurableApplicationContext 接口中的 start()方法启动 ApplicationContext时,
* 该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
* @author Administrator
*
*/
public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>{ @Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent start!!");
} }

下面是 CStopEventHandler.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.szxy;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStoppedEvent; /**
* ContextStoppedEvent:大专栏  Spring中的事件处理span>
* 当使用 ConfigurableApplicationContext 接口中的 stop() 方法停止 ApplicationContext 时,
* 发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
* @author Administrator
*
*/
public class CStopEventHandler implements ApplicationListener<ContextStoppedEvent>{ @Override
public void onApplicationEvent(ContextStoppedEvent event) {
System.out.println("ContextStoppedEvent stop!!");
} }

下面是 Start.java 文件的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.szxy;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Start {
public static void main(String[] args) {
//加载spring配置文件,初始化所有的bean
ClassPathXmlApplicationContext ac =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //启动spring容器
ac.start(); HelloSpringEvent hello = ac.getBean("helloSpringEvent", HelloSpringEvent.class);
System.out.println(hello.getMsg()); //停止spring容器
ac.stop();
}
}

下面是配置文件 applicationContext.xml 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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.xsd"> <bean id="helloSpringEvent" class="com.szxy.HelloSpringEvent">
<property name="msg">
<value>Test SpringEvent!!</value>
</property>
</bean> <bean id="cStartEventHandler" class="com.szxy.CStartEventHandler"></bean> <bean id="cStopEventHandler" class="com.szxy.CStopEventHandler"></bean> </beans>

一旦你完成了创建源和 bean 的配置文件,我们就可以运行该应用程序。如果你的应用程序一切都正常,将输出以下消息:

1
2
3
4
HelloSpringEvent 初始化
ContextStartedEvent start!!
Test SpringEvent!!
ContextStoppedEvent stop!!

注意:

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

例如:

​ CStartEventHandler类的监听函数处理中加入一个阻塞调用System.in.read();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.szxy;

import java.io.IOException;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent; /**
* ContextStartedEvent:
* 当使用 ConfigurableApplicationContext 接口中的 start()方法启动 ApplicationContext时,
* 该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
* @author Administrator
*
*/
public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>{ @Override
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent start!!");
try {
System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

运行结果:

1
2
HelloSpringEvent 初始化
ContextStartedEvent start!!

可以看出进程被阻塞了,程序不会往下继续执行

参考:

https://wiki.jikexueyuan.com/project/spring/event-handling-in-spring.html

Spring中的事件处理的更多相关文章

  1. Spring 中的事件处理

    Spring 中的事件处理 Spring 的核心是 ApplicationContext,它负责管理 beans 的完整生命周期.当加载 beans 时,ApplicationContext 发布某些 ...

  2. JAVA面试题:Spring中bean的生命周期

    Spring 中bean 的生命周期短暂吗? 在spring中,从BeanFactory或ApplicationContext取得的实例为Singleton,也就是预设为每一个Bean的别名只能维持一 ...

  3. spring事件驱动模型--观察者模式在spring中的应用

    spring中的事件驱动模型也叫作发布订阅模式,是观察者模式的一个典型的应用,关于观察者模式在之前的博文中总结过,http://www.cnblogs.com/fingerboy/p/5468994. ...

  4. Spring(九)之事件处理

    Spring的核心是ApplicationContext,它管理bean的完整生命周期.ApplicationContext在加载bean时发布某些类型的事件.例如,ContextStartedEve ...

  5. Spring 中的事件机制

    说到事件机制,可能脑海中最先浮现的就是日常使用的各种 listener,listener去监听事件源,如果被监听的事件有变化就会通知listener,从而针对变化做相应的动作.这些listener是怎 ...

  6. Velocity初探小结--Velocity在spring中的配置和使用

    最近正在做的项目前端使用了Velocity进行View层的数据渲染,之前没有接触过,草草过了一遍,就上手开始写,现在又回头细致的看了一遍,做个笔记. velocity是一种基于java的模板引擎技术, ...

  7. Spring中Bean的作用域、生命周期

                                   Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...

  8. Spring中Bean的实例化

                                    Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...

  9. 模拟实现Spring中的注解装配

    本文原创,地址为http://www.cnblogs.com/fengzheng/p/5037359.html 在Spring中,XML文件中的bean配置是实现Spring IOC的核心配置文件,在 ...

随机推荐

  1. P2P平台疯狂爆雷后,你的生活受到影响了吗?

    最近这段时间P2P爆雷的新闻和报道一直占据着各大财经和科技媒体的重要位置.而据网贷之家数据显示,截至2018年7月底,P2P网贷行业累计平台数量达到6385家(含停业及问题平台),其中问题平台累计为2 ...

  2. Bless All

    # php code $i = 2333 $myJXOI = JXOI() while($i == 2333){ ++myJXOI.score , ++myJXOI.rp , --myJXOI.常数 ...

  3. 杨辉三角(C语言)

    杨辉三角 杨辉三角,是二项式系数在三角形中的一种几何排列,中国南宋数学家杨辉1261年所著的<详解九章算法>一书中出现.在欧洲,帕斯卡(1623----1662)在1654年发现这一规律, ...

  4. 5)PHP,可变变量

    所谓可变变量,就是一个变量的名,又是一个变量. 可变变量的语法是php的很特殊的语法——其他语言中少见. $v1 = “abc”; //这是一个字符串变量,其内容是字符串“abc” $abc = ; ...

  5. Intellij IDEA中mybatis-generator自动生成

    一.在maven工程中的resource中创建generatorConfig.xml 二.配置generatorConfig.xml: <?xml version="1.0" ...

  6. Codeforces Round #606 E

    题:https://codeforces.com/contest/1277/problem/E 题意:给定无向图,求有多少个pair之间的简单路径一定要经过给定的点a和b(pair中任何一个都不是a或 ...

  7. rsync实战(二)

    加两个需求:1.增加一个模块2.每个模块不同的用户名 步骤: .修改配置文件/etc/rsyncd.conf [backup] comment = commit path = /backup auth ...

  8. javascript 的七种基本数据类型

    六种基本数据类型 undefined null string boolean number symbol(ES6) 一种引用类型 Object 为什么要引入 Symbol? ES5的对象中的属性名是字 ...

  9. [LC] 796. Rotate String

    We are given two strings, A and B. A shift on A consists of taking string A and moving the leftmost ...

  10. Nginx的下载与安装

    .创建文件输入网页中需要复制的 cat >/etc/yum.repos.d/nginx.repo<<EOF [nginx-stable] name=nginx stable repo ...