文章目录

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. kubectl 常用命令一

    1.kubectl logs <options>  <PodName> -f -p, --previous --since= No. --since-time= --tail ...

  2. git 提交部分修改的文件,以及如何撤回已经add的文件

    命令 1.git status //查看修改文件状态 ,可以看到哪些add了哪些没add 注意:如果此时出现了有些文件不想添加到暂存区却添加进去了,需要撤回 git reset HEAD 全部撤销gi ...

  3. pytHon深度学习(3.4)

    keras绘制损失函数曲线 # -*- coding: utf-8 -*-'''Trains a simple deep NN on the MNIST dataset.Gets to 98.40% ...

  4. POJ 3273 Monthly Expense二分查找[最小化最大值问题]

    POJ 3273 Monthly Expense二分查找(最大值最小化问题) 题目:Monthly Expense Description Farmer John is an astounding a ...

  5. 二、NOSQL之Memcached缓存服务实战精讲第一部

    1.Memcached是一套数据缓存系统或软件. 用于在动态应用系统中缓存数据库的数据,减少数据库的访问压力,达到提升网站系统性能的目的:Memcached在企业应用场景中一般是用来作为数据库的cac ...

  6. idea 连接mysql报错:Access denied for user 'root'@'localhost'(using password:YES)。

    这两天在idea中开发Web项目时,连接MYSQL数据库,出现问题:Access denied for user 'root'@'localhost'(using password:YES).    ...

  7. CNN Mini-Fashion数据集以及Pytorch初体验

    下载Fasion-MNIST数据集 Fashion-MNIST是一个替代原始的MNIST手写数字数据集的另一个图像数据集. 它是由Zalando(一家德国的时尚科技公司)旗下的研究部门提供.其涵盖了来 ...

  8. Linux磁盘空间满的诡异问题解决方案

    问题描述: 今天登上一台服务器,df -h 发面根目录磁盘已经满了 解决过程: cd / du -sh *  发现并没有大文件,占用的空间没多大 根据经验,先通过lsof | grep deleted ...

  9. n的m划分

    n的m划分: dp[i][j]表示j的i划分,也就是将j颗球放入i个袋子里面,最后的答案是dp[m][n] 状态转移方程为dp[i][j]=dp[i-1][j]+dp[i][j-i]; 划分方法有两种 ...

  10. Redis为什么这么快以及持久化机制

    1.首先我们谈一下为什么Redis快: 一. Redis是纯内存数据库,一般都是简单的存取操作,线程占用的时间很多,时间的花费主要集中在IO上,所以读取速度快. 二. 再说一下IO,Redis使用的是 ...