6. Spring4.x 事件 ApplicationEvent

ApplicationEvent的基本使用

  1. 自定义事件
package com.xiaohan.event;

import org.springframework.context.ApplicationEvent;

public class DemoEvent extends ApplicationEvent{

    private String msg;

    public DemoEvent(Object source,String msg) {
        super(source);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
  1. 事件监听器
package com.xiaohan.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

//指定监听的事件类型
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

    // 接收消息 并处理消息
    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        String msg = demoEvent.getMsg();
        System.err.println(this.getClass().getName() + "监听到了" + demoEvent.getSource().getClass().getName() + "的消息: " + msg);
    }
}
  1. 事件发布类
package com.xiaohan.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoPublisher {

    // 注入Spring容器
    @Autowired
    private ApplicationContext ac;

    public void publish(String msg) {
        ac.publishEvent(new DemoEvent(this, msg));
    }
}
  1. 配置类
package com.xiaohan.event;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.xiaohan.event")
public class EventConfig {
}
  1. Main测试类
package com.xiaohan.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

// 事件   ApplicationEvent
public class Main {
    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(EventConfig.class);
        DemoPublisher demoPublisher = ac.getBean(DemoPublisher.class);
        demoPublisher.publish("hello application event");
    }
}

输出

com.xiaohan.event.DemoListener监听到了com.xiaohan.event.DemoPublisher的消息: hello application event
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,951评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,268评论 25 708
  • #微写作#02 晚上敷了一贴面膜,同时写写东西。新买的面膜可以感觉到补水作用,皮肤可以很快吸收,润润的感觉非常不错...
    Becalm阅读 126评论 0 0
  • 抽一张复原卡代表在亲密关系中,你的需求是…… 副卡:代表,所以你常常表现的…… 1.在亲密关系中我的需求是:一个家...
    我是蕙質蘭心阅读 214评论 0 0