文章目录

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. 二、提高期(Upping the Ante)

    二.提高期(Upping the Ante) Upping the Ante?这可是第四阶段的词.没办法,Greg Thomson用这个词代表第二阶段,看着喜欢,继续沿用. 经过两三个月的“图象+声音 ...

  2. 将keras的h5模型转换为tensorflow的pb模型

    h5_to_pb.py from keras.models import load_model import tensorflow as tf import os import os.path as ...

  3. AtCoder Beginner Contest 129

    ABCD 签到(A.B.C过水已隐藏) #include<bits/stdc++.h> using namespace std; ; int n,m,ans,f1[N][N],f2[N][ ...

  4. Python 学习笔记:根据输入年月区间,返回期间所有的月份

    目的: 给定一个年月区间,比如:2019.01 至 2019.05,要求返回一个包含期间所有的月份的列表,比如:['2019.01', '2019.02', '2019.03', '2019.04', ...

  5. 吴裕雄--天生自然 pythonTensorFlow图形数据处理:输入文件队列

    import tensorflow as tf # 1. 生成文件存储样例数据. def _int64_feature(value): return tf.train.Feature(int64_li ...

  6. [思路笔记]WEB安全之漏洞挖掘

    记录自己在实际渗透测试以及漏洞挖掘中会用到的思路和方法.不断完善,尽量以系统的方式展现程序化式的漏洞挖掘.由于各种原因,不便公开. 通用策略 1.信息搜集 : 数据挖掘.业务挖掘 数据: 邮箱.手机号 ...

  7. G. Petya and Graph(经典项目与项目消耗问题)(网络流)

    题:https://codeforces.com/contest/1082/problem/G 题意:给定有边权和点权的图,问你选一些边,然sum边-sum点最大(点权被多次用为公共点只会减一次) 分 ...

  8. nginx 配合jersey+netty的奇怪问题

    角色 client proxy nginx server jersey+netty 问题表现 client 直接请求server 正常,返回准确json数据 jsondat client->ng ...

  9. [USACO09DEC]牛收费路径Cow Toll Paths(floyd、加路径上最大点权值的最短路径)

    https://www.luogu.org/problem/P2966 题目描述 Like everyone else, FJ is always thinking up ways to increa ...

  10. RegexUtil

    package org.linlinjava.litemall.core.util; import java.util.ArrayList; import java.util.Collections; ...