文章目录

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. My97DatePicker日历插件

    My97DatePicker具有强大的日期功能,能限制日期范围,对于编写双日历比较简便. 注意事项: My97DatePicker目录是一个整体,不可以破坏 My97DatePicker.html 是 ...

  2. 翻译——1_Project Overview, Data Wrangling and Exploratory Analysis-checkpoint

    为提高提高大学能源效率进行建筑能源需求预测 本文翻译哈佛大学的能源分析和预测报告,这是原文 暂无数据源,个人认为学习分析方法就足够 内容: 项目概述 了解数据 探索性分析 使用不同的机器学习方法进行预 ...

  3. python的稀疏矩阵计算

    尽量避免稀疏矩阵, 加快计算. 比如计算稀疏矩阵S的F范数 a = norm(S, 'fro'), 方法1效率比方法2高很多. 方法 1 import numpy as np a = np.linal ...

  4. 吴裕雄--天生自然python TensorFlow图片数据处理:解决TensorFlow2.0 module ‘tensorflow’ has no attribute ‘python_io’

    tf.python_io出错 TensorFlow 2.0 中使用 Python_io 暂时使用如下指令: tf.compat.v1.python_io.TFRecordWriter(filename ...

  5. [SDOI2019]世界地图(kruskal重构树+虚树)

    通过子任务1.3十分显然,子任务4实际上就是线段树,和我下午写的[SDOI2015]道路修建一模一样,堪称“我抄我自己”,不会的可以先做一下这个题. 然后考虑正解,参考了zhoushuyu的博客,首先 ...

  6. 基础篇四:Ngnix安装

    然后直接 yum  install nginx 安装nginx

  7. linux chmod命令修改文件权限

    在linux中,使用chmod命令修改一个文件的权限. 首先,我们查看一个文件夹下所有文件的权限 ls -l linux文件或目录的权限分为,读.写.可执行三种权限.文件访问的用户类别分为,文件创建者 ...

  8. 在SpringBoot中使用Junit测试

    一:加入依赖 <dependency> <groupId>junit</groupId> <artifactId>junit</artifactI ...

  9. 整理汇总系统中空值的使用方法,后台+jsp

    一.后台: 1. entity.getStringValue().isEmpty()://字符串自带方法,未发现非空方法实现原理:判断值的长度 public boolean isEmpty() { r ...

  10. jenkins-自定义工作空间目录