---
title: "spring事件处理框架"
author: "rock"
date: "2010-05-18T10:20:14Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2010-05-18T10:21:10Z"
id: 668726
url: "https://rock.iteye.com/blog/668726"
---

## 1 Spring 事件处理框架

 

通过 ApplicationEvent 类和ApplicationListener 接口，Event 事件处理会在ApplicationContext 中进行。如果一个bean 实现了ApplicationListener 接口，当ApplicationEvent 被ApplicationContext 发布时，这个bean 就会被通知。这在本质上相当于标准的观察者模式。

 

ApplicationContext 通过方法publishEvent() 来发布事件，该方法的参数是继承了ApplicationEvent 的事件定义类的实例。所有的监听者都会同步的接收到发布的事件，这意味着当publishEvent （）调用时程序会阻塞，直到所有的监听者都处理完毕（也可能通过实现ApplicationEventMulticaster 来提供一个交替的事件发布策略，Spring 的 SimpleApplicationEventMulticaster 是他的一个实现，内部使用 TaskExecutor 以多线程的方式异步调用事件监听 ）。如果有事物上下文，监听者的事务会处在发布者的事物当中。

 

 

以下是一个实例：

事件定义类

public abstract class BlackListEvent extends ApplicationEvent {

        public BlackListEvent(Object source) {

           super (source);

        }       

public final Black get Black () {

           return ( Black )getSource();

        }

 

}

事件发布类：

public class EmailBean implements ApplicationContextAware {

private List blackList;

private ApplicationContext ctx;

public void setBlackList(List blackList) {

this.blackList = blackList;

}

public void setApplicationContext(ApplicationContext ctx) {

this.ctx = ctx;

}

public void sendEmail(String address, String text) {

if (blackList.contains(address)) {

Black black=new Black(address, text);

                      BlackListEvent event = new BlackListEvent(black);

                      ctx.publishEvent(event);

     }

*// send email...*

}

}

事件监听类：

public class BlackListNotifier implements ApplicationListener {

private String notificationAddress;

public void setNotificationAddress(String notificationAddress) {

this.notificationAddress = notificationAddress;

}

public void onApplicationEvent(ApplicationEvent event) {

if (event instanceof BlackListEvent) {

*// notify appropriate person...*

}

}

}

 

bean 配置文件：

&lt;bean id="emailer" class="example.EmailBean"&gt;

&lt;property name="blackList"&gt;

&lt;list&gt;

&lt;value&gt;black@list.org&lt;/value&gt;

&lt;value&gt;white@list.org&lt;/value&gt;

&lt;value&gt;john@doe.org&lt;/value&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

&lt;bean id="blackListListener" class="example.BlackListNotifier"&gt;

&lt;property name="notificationAddress" value="spam@list.org"/&gt;

&lt;/bean&gt;

 

## 2 后续问题

   Aop 替代：与 aop 实现方式的比较。（减小耦合）

  同步事件：可以处理 before ， after 等事件。（ spring 为同步）

   异步事件：事件异步处理框架 , 考虑事务问题。

   事件监听管理：集中管理还是分散管理（不同的设计方式）

                 集中管理优点：方便查找事件监听，利于维护

                 分散管理： 更高程度上解耦