Spring 注解事件Event

Stella981
• 阅读 447

String event

从Spring的4.2版本后,开始支持注解来进行事件广播接收,这使得我们非常方便 当然了Spring也支持JMS消息中间件,这个就可以做多个系统集成了,感觉有点偏题了,先看看事件怎么通过注解来开发


基础支持

先来看看支持哪些默认事件

Event

描述

ContextRefreshedEvent

ApplicationContext或者叫spring被初始化或者刷新initialized会触发该事件

ContextStartedEvent

spring初始化完,时触发

ContextStoppedEvent

spring停止后触发,一个停止了的动作,可以通过start()方法从新启动

ContextClosedEvent

spring关闭,所有bean都被destroyed掉了,这个时候不能被刷新,或者从新启动了

RequestHandledEvent

请求经过DispatcherServlet时被触发,在request完成之后


程序1(Service)

先看看程序

ApplicationEventPublisher这个是spring的东西,需要注入来进行发送 因为实现了ApplicationEventPublisherAware所以setApplicationEventPublisher这个方法会自动帮我们调用,拿到广播发送者

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */
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;
    }

    /**
     * 具体广播类
     * @param address
     * @param text
     */
    public void sendEmail(String address, String text) {
        if (blackList.contains(address)) {
            BlackListEvent event = new BlackListEvent(this, address, text);
            publisher.publishEvent(event);
            return;
        }
        // send email...
    }
}

程序2(Event)

这里也是需要继承ApplicationEvent,并且里面可以实现自己的一些必要参数等等,让在收到广播时进行获取,当然通过source也可以的

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */
public class BlackListEvent extends ApplicationEvent {
    private String address;
    private String test;

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}

程序3(receiver)

用spring还是得遵循他一套规范,那么接收者的,还得实现ApplicationListener接口,那么所有收到泛型广播的对象,都会转发onApplicationEvent接口里面来的

当然了spring想得很周全,不一定通过实现ApplicationListener这个类,在bean类里面加入注解@EventListener

/**
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */
public class BlackListNotifier implements ApplicationListener<BlackListEvent> {

    private String notificationAddress;

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

    @EventListener
    public void onApplicationEvent(BlackListEvent event) {
        // notify appropriate parties via notificationAddress...
        System.out.println("onApplicationEvent, some thing I receive:" + event.getAddress() + ",text:" + event.getTest());
    }

    @EventListener(condition = "#event.test == 'foo'")
    public void onApplicationCustomerEvent(BlackListEvent event) {
        System.out.println("onApplicationCustomerEvent,some thing I receive:" + event.getAddress() + ",text:" + event.getTest());
        // notify appropriate parties via notificationAddress...
    }

    @EventListener({ContextStartedEvent.class, ContextRefreshedEvent.class})
    public void handleContextStart() {
        System.out.println("-------------handleContextStart");

    }
    
    /**
     * 参数可以给BlackListEvent 可以不给
     */
    @EventListener(classes = {BlackListEvent.class})
    public void handleBlackListEvent() {
        System.out.println("-------------handleBlackListEvent");
    }
}

@EventListener

解析一下这个注解怎么用,犹如上面的程序,除了实现接口外,可以通过@EventListener注解来实现

  • condition可以使用SpEL表达式,就是当满足条件才执行
  • classes当触发event对象是这个class才会被执行

程序4(config bean)

这里主要对一些服务以及接受广播bean的注册,以便接受

/**
 * 配置
 * @author Carl
 * @date 2016/8/28
 * @modify 版权所有.(c)2008-2016.广州市森锐电子科技有限公司
 */
@Configuration
public class AppConfig {
    @Bean
    public EmailService emailService() {
        EmailService s = new EmailService();
        List<String> emails = new ArrayList<>(3);
        emails.add("known.spammer@example.org");
        emails.add("known.hacker@example.org");
        emails.add("john.doe@example.org");
        s.setBlackList(emails);
        return s;
    }

    @Bean
    public BlackListNotifier notifier() {
        BlackListNotifier notifier = new BlackListNotifier();
        notifier.setNotificationAddress("blacklist@example.org");
        return notifier;
    }
}

个人学习记录说得不对麻烦大家谅解,或进行评论补充

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Easter79 Easter79
2年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这