Spring 框架笔记—4.16.2 标准与自定义事件

标签: spring 框架 笔记 | 发表时间:2019-08-31 00:02 | 作者:loris_jand
出处:https://www.iteye.com
            Spring 框架笔记—4.16.2 标准与自定义事件

Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. If a bean that implements the ApplicationListener interface is deployed into the context, every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified. Essentially, this is the standard Observer design pattern. Spring 内置提供的标准事件包括:

ContextRefreshedEvent
Published when the ApplicationContext is initialized or refreshed, for example, using the refresh() method on the ConfigurableApplicationContext interface. "Initialized" here means that all beans are loaded, post-processor beans are detected and activated, singletons are pre-instantiated, and the ApplicationContext object is ready for use. As long as the context has not been closed, a refresh can be triggered multiple times, provided that the chosen ApplicationContext actually supports such "hot" refreshes. For example, XmlWebApplicationContext supports hot refreshes, but GenericApplicationContext does not.

ContextStartedEvent
Published when the ApplicationContext is started, using the start() method on the ConfigurableApplicationContext interface. "Started" here means that all Lifecycle beans receive an explicit start signal. Typically this signal is used to restart beans after an explicit stop, but it may also be used to start components that have not been configured for autostart , for example, components that have not already started on initialization.

ContextStoppedEvent
Published when the ApplicationContext is stopped, using the stop() method on the ConfigurableApplicationContext interface. "Stopped" here means that all Lifecycle beans receive an explicit stop signal. A stopped context may be restarted through a start() call.

ContextClosedEvent
Published when the ApplicationContext is closed, using the close() method on the ConfigurableApplicationContext interface. "Closed" here means that all singleton beans are destroyed. A closed context reaches its end of life; it cannot be refreshed or restarted.

RequestHandledEvent
A web-specific event telling all beans that an HTTP request has been serviced. This event is published after the request is complete. This event is only applicable to web applications using Spring’s DispatcherServlet.

创建自己的事件只需要继承ApplicationEvent类,如下所示:
public class BlackListEvent extends ApplicationEvent {

    private final String address;
    private final String test;

    public BlackListEvent(Object source, String address, String test) {
        super(source);
        this.address = address;
        this.test = test;
    }

    // accessor and other methods...

}

如果我们要发布上述事件,我们需要调用 ApplicationEventPublisher接口的publishEvent()方法,通常我们可以创建一个类实现ApplicationEventPublisherAware接口,并将它注册为Bean.示例如下:
public class EmailService implements ApplicationEventPublisherAware {

    private List<String> blackList;
    private ApplicationEventPublisher publisher;

    public void setBlackList(List<String> blackList) {
        this.blackList = blackList;
    }

    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void sendEmail(String address, String text) {
        if (blackList.contains(address)) {
            BlackListEvent event = new BlackListEvent(this, address, text);
            publisher.publishEvent(event);
            return;
        }
        // send email...
    }

}

在配置时,Spring容器会探测到EmailService 实现了ApplicationEventPublisherAware接口并自动的调用setApplicationEventPublisher()方法。实际上这个方法的参数就是Spring容器本身;通过ApplicationEventPublisher 接口与我们便可以与应用程序上下文进行交互。

如果要消费这个事件,则需要编写一个类实现ApplicationListener 接口并将之注册为Spring 的bean.以下示例阐述了这一点。
public class BlackListNotifier implements ApplicationListener<BlackListEvent> {

    private String notificationAddress;

    public void setNotificationAddress(String notificationAddress) {
        this.notificationAddress = notificationAddress;
    }

    public void onApplicationEvent(BlackListEvent event) {
        // notify appropriate parties via notificationAddress...
    }

}


Notice that ApplicationListener is generically parameterized with the type of your custom event, BlackListEvent. This means that the onApplicationEvent() method can remain type-safe, avoiding any need for downcasting. You may register as many event listeners as you wish, 需要注意的一点是所有事件监听都是同步的接收事件.这就表示 publishEvent() 方法被阻塞直到所有监听器完成事件处理. 这种同步和单线程方式的一个优点是,当监听器接收到事件时,如果发现事务上下文可用,那么它将在发布服务者的事务上下文中操作。如果我们想要定制事件发布的一些策略,可了解Spring的ApplicationEventMulticaster接口。

已有 0 人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐



相关 [spring 框架 笔记] 推荐:

Spring 框架笔记—4.16.2 标准与自定义事件

- - 企业架构 - ITeye博客
            Spring 框架笔记—4.16.2 标准与自定义事件. If a bean that implements the ApplicationListener interface is deployed into the context, every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

Spring笔记 - Spring Expression Language (SpEL表达式)

- - CSDN博客架构设计推荐文章
数字5       . 联合方式  . 浮点型      .

Spring Batch学习笔记

- - 博客园_首页
  和传统的批处理(Batch Processing)相比,Spring Batch虽然有很大的不同,但是归根结底,都是顺序地执行一些列任务. 你用Spring Batch可以读取一个TXT文件的内容,然后将处理之后的数据放到数据库里,反之亦然.    Spring Batch任务处理的核心组件有Job、Step、Tasklet、JobLuncher和JobRepository等.

spring面试笔记(转)

- - CSDN博客推荐文章
一、spring工作原理:. 1.spring mvc请所有的请求都提交给DispatcherServlet,它会委托应用系统的其他模块负责负责对请求进行真正的处理工作. 2.DispatcherServlet查询一个或多个HandlerMapping,找到处理请求的Controller. 3.DispatcherServlet请请求提交到目标Controller.

微服务框架Spring Cloud介绍 Part2: Spring Cloud与微服务

- - skaka的博客
之前介绍过 微服务的概念与Finagle框架, 这个系列介绍Spring Cloud.. Spring Cloud还是一个相对较新的框架, 今年(2016)才推出1.0的release版本. 虽然Spring Cloud时间最短, 但是相比我之前用过的Dubbo和Finagle, Spring Cloud提供的功能最齐全..

Spring框架学习【基础知识】

- - CSDN博客推荐文章
1.在java开发领域,Spring相对于EJB来说是一种轻量级的,非侵入性的Java开发框架,曾经有两本很畅销的书《Expert one-on-one J2EE Design and Development》和《Expert one-on-one J2EEdevelopment without EJB》是java高手进阶必看的宝典,Spring就是从这两本书的理论发展起来的.

Spring Data JPA,基础学习笔记.

- - ITeye博客
最好先学习 JPA 方面的知识....在这里使用的是 Hibernate. 也已经使用了一段时间,看什么都不如看官方文档,我这里也只是写个笔记记录一下,如果能帮助到其他人,很开心 .算是个 demoshow 吧.这里也只写了一些我觉得比较有用的地方.其他一些使用知识,请参见官方文档:http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/.

spring的事务管理笔记

- - 企业架构 - ITeye博客
首先,事务管理是保证数据操作的事务性 ACID(即原子性、一致性、隔离性、持久性).        对于使用支持事务管理的数据库时,普通的jdbc的连接没用配置事务也可以保存变更,原因在于连接的属性autocommit设置了true,即自动提交了事务.        而对于某些数据库本身没有对事务的支持,那么事务管理也是一纸空谈没有必要进行配置(有例外),如MySQL的MyISAM没有事务管理的支持.

spring cloud stream使用笔记 - 简书

- -
以前我们在spring boot中构建一个消息驱动的微服务应用,通常会使用rabbitMQ或是kafka来做消息中间件,应用中均需代码实现具体消息中间件的通信细节. 此时如果再更换一个新的消息中间件,这会我们又需新增这些通信代码,写起来会比较繁琐,而stream出现就是为了简化这一过程. 它是一个构建消息驱动的微服务应用的框架.

盘点 Spring Security 框架中的八大经典设计模式

- - SegmentFault 最新的文章
上次有小伙伴建议,源码分析太枯燥了,要是能够结合设计模式一起来,这样更有助于大家理解 Spring Security 源码,同时还能复习一波设计模式. 因此松哥今天就试着整一篇,和大家来聊一聊 Spring Security 中涉及到的设计模式,不过 Spring Security 中涉及到的设计模式还是非常多的,松哥这里讲几个,剩下的欢迎小伙伴们留言补充.