1. 程式人生 > >spring的自定義監聽事件

spring的自定義監聽事件

前言:

今天寫程式碼的時候遇到了監聽器,然後我就鬼使神差的翻了一下Spring框架文件,看到了自定義監聽事件,下面是我的收穫分享。

標準事件

spring中自帶有5種標準事件,ContextRefreshedEvent,ContextStartedEvent,ContextStoppedEvent,ContextClosedEvent,RequestHandledEvent。需要了解的話,可自行網上搜索或者看官方文件。

自定義事件

流程:

  1. 繼承ApplicationEvent ,建立自定義事件。
  2. 釋出我們的自定義事件,一般通過實現ApplicationEventPublisherAware 介面來完成。
  3. 定義事件監聽器,一般是實現ApplicationListener介面或者使用@EventListener註解。

具體實現與程式碼展示

首先繼承ApplicationEvent類,建立我們的自定義事件。

public class MyApplicationEvent extends ApplicationEvent{

    private static final long serialVersionUID = -543396148689229096L;

    private final String address;

    public final String test;

    public
MyApplicationEvent(Object source ,String address ,String test) { super(source); this.address = address; this.test = test; } @Override public String toString() { return "MyApplicationEvent [address=" + address + ", test=" + test + "]"; } // accessor and other methods...
}

想要釋出我們的自定義事件,就需要呼叫ApplicationEventPublisher類中的publishEvent()方法 。官方文件中是叫我們建立一個實現ApplicationEventPublisherAware的類,並且註冊為spring中的bean。

@Component
public class MyApplicationEventService implements ApplicationEventPublisherAware{

    private List<String> blackList;
    private ApplicationEventPublisher publisher;

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

    public void sendEmail(String address, String text) {
        blackList = new ArrayList<>();
        blackList.add("[email protected]");
        blackList.add("[email protected]");
        blackList.add("[email protected]");
        if (blackList.contains(address)) {
            publisher.publishEvent(new MyApplicationEvent(this, address, text));
            return;
        }
        // send email...
    }

    public void testListener(String address, String text) {
        MyApplicationEvent event = new MyApplicationEvent(this, address, text);
        publisher.publishEvent(event);
    }

}

在配置的時候,Spring容器會檢測到這個MyApplicationEventService實現 ApplicationEventPublisherAware並自動呼叫 setApplicationEventPublisher()。實際上,傳入的引數將是Spring容器本身; 您只需通過其ApplicationEventPublisher介面與應用程式上下文進行 互動。

完成釋出,就要寫事件監聽器,建立一個實現 ApplicationListener的類,並且註冊為spring中的bean。

@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>{

    public void onApplicationEvent(MyApplicationEvent event) {
        System.out.println("my listener start");
        System.out.println(event.toString());
        System.out.println("my listener end");
    }

}

onApplicationEvent中編寫你的監聽邏輯。

總的實現效果就是,你一使用MyApplicationEventService類的sendEmail()和testListener()方法,監聽器就會觸發。寫一個controller來測試一下效果。

@RestController
@RequestMapping("/listener")
public class ListenerController {

    @Autowired
    private MyApplicationEventService myApplicationEventService;

    @GetMapping("/listener")
    public String testMyListener() {
        /*myApplicationEventService.sendEmail("[email protected]", "123123"); */
                            myApplicationEventService.testListener("[email protected]", "123");
        return "SUCCESS";
    }   
}
my listener start
MyApplicationEvent [address=john.doe@example.org, test=123]
my listener end

這說明我們的自定義事件和監聽器起作用了。

使用註解來定義監聽器

@Component
public class MyTestListener {

    @EventListener
    public void testListenr(MyApplicationEvent event) {
        System.out.println("my listener start");
        System.out.println(event.toString());
        System.out.println("my listener end");
    }

}

MyTestListener 類實現的效果和MyApplicationListener 類一樣。

使用註解還有兩好處

1 . 你可以在一個註解中監聽多種事件

@EventListener({ContextRefreshedEvent.class, MyApplicationEvent .class})
    public void testListenr() {
        System.out.println("my listener start");
        System.out.println("my listener end");
    }

2 . 還可以通過condition註釋的屬性新增額外的執行時過濾,該過濾器定義一個SpEL表示式。

@EventListener(condition="#event.test == '123'")
    public void testListenr(MyApplicationEvent event) {
        System.out.println("my listener start");
        System.out.println(event.toString());
        System.out.println("my listener end");
    }

相關推薦

Spring 初探(五)(Spring Bean 自動裝配與定義事件

現在通行的使用bean的方法是不通過xml進行配置,而僅僅採用java 內建的類指明bean及相應的依賴關係,下面展開敘述。 @Configuration可以宣告某個類是作為配置類,在這樣的類中 通過@Bean進行修飾的方法可以返回相應的bean類 通過由Annotatio

spring定義事件

前言: 今天寫程式碼的時候遇到了監聽器,然後我就鬼使神差的翻了一下Spring框架文件,看到了自定義監聽事件,下面是我的收穫分享。 標準事件 spring中自帶有5種標準事件,ContextRefreshedEvent,ContextStartedEv

RecycleView的使用+定義事件

eight style width add text boolean listen long group 最近使用了RecycleView,發下這個控件十分好用,替代了listView和GridView,包括適配器都很方便。 效果如下: 具體使用如下所示: 1 co

移動端app,mui頁面互動之定義事件

b.html程式碼 //引數1:處罰這個事件的頁面物件 //引數2:自定義事件名稱,自取 //引數3:傳值 Object 物件的形式 var homePage = plus.webview.currentWebview().opener();//獲取a頁面物件 var a = 1; mui.fi

Vue父子元件通訊,props和定義

1.子元件通過props接收父元件中的值,插入子元件中會跟隨父元件而變化。(:x="num")--->頁面中插入{{x}} 2.如果只想變接收過來的值,而不改變父元件的,則吧接收過來的值存一下。(newx:this.x)--->頁面中插入{{newx}} 3.

android定義

自定義監聽分為三個步驟 1、定義監聽介面 public interface OnClickListener{ void onClickListener(int positon); } 2、在需要監聽事件的類中新增監聽方法比如MyAdapter中,並傳遞引數 class MyA

RabbitMQ高階特性-消費端定義

消費端自定義監聽 在之前的程式碼演示中, consumer進行消費時 ,都是使用while迴圈進行訊息消費, 然後使用consumer.nextDelivery()方法獲取下一條訊息 但是在實際工作中, 使用自定義的Consumer更加的方便, 解耦性也更加的強, 實現

spring 定義事件發布及(簡單實例)

講解 new 繼承 概念 接口 處理 啟動 lca 事件對象 前言: Spring的AppilcaitionContext能夠發布事件和註冊相對應的事件監聽器,因此,它有一套完整的事件發布和監聽機制。 流程分析: 在一個完整的事件體系中,除了事件和監聽器以外,還應該有3個概

vue 組件 子向父親通信用定義方法用事件

自定義 let 事件監聽 () 有理 mode head con methods <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>Title

事件和window.history以及定義創建事件

lac 瀏覽器 捕獲 tps details push AD his listener 1.事件監聽window.addEventListener方法: Window.addEventListener(event, function, useCapture); useC

JS過渡結束事件及使用定義事件解決兼容問題的方法

定義 inf mage image 過渡 解決 技術分享 分享 img 1.JS過渡結束監聽事件 2.自定義事件解決兼容問題 JS過渡結束監聽事件及使用自定義事件解決兼容問題的方法

觀察者模式下es6的實現(定義事件

定義 觀察者模式:又叫釋出訂閱模式,多個觀察者可以實時監聽一個主題物件,而javascript中最常用的實現方式是事件觸發機制。 es6實現: 要知道需要有什麼東西,類和建構函式是es6中基本的物件結構 class BaseEvent {   constructor() {} } 首先類中要能儲

jquery 定義input輸入事件

網上一段JS,考來的,自定義監聽: $.event.special.valuechange = { teardown: function (namespaces) { $(this).unbind('.valuechange')

Android中定義ScrollView的滑動事件

專案結構: 1.LazyScrollView類(自定義ScrollView) package android.zhh.com.myapplicationscrollview; /** * Created by sky on 2017/3/19. */ impor

Android中定義ScrollView的滑動事件,並在滑動時漸變標題欄背景顏色

效果圖 滑動前: 滑動中: 滑動到底部: 專案結構 ObservableScrollView package com.jukopro.titlebarcolor; import android.content.Context; import android.u

h5定義滾動條並事件

程式碼加註釋如下所示: <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title><sty

Android完全定義控制元件並且實現事件

本篇文章帶來Android的完全自定義控制元件。載體是自定義一個開關的控制元件,並且能夠響應事件,首先我們先創一個專案,名字就叫ToggleView,修改MainActivity public class MainActivity extends Acti

Spring事件 ApplicationListener 和 ApplicationEvent 用法

scan bsp string bject wired static final HA AD spring事件(application event)為Bean與Bean之間的消息通信添加了支持,當一個Bean處理完一個任務之後,希望另一個Bean知道並能做相應的處理,這時我

Spring事件 ApplicationListener 和 ApplicationEvent 用法及呼叫過程詳解

ApplicationListener呼叫過程詳解: https://blog.csdn.net/u014263388/article/details/78996509 使用場景 在一些業務場景中,當容器初始化完成之後,需要處理一些操作,比如一些資料的載入、初始化快取、特定任務的註冊等等。這

Spring事件ApplicationListener和ApplicationEvent及@EventListener用法

什麼是ApplicationContext?  它是spring的核心,Context我們通常解釋為上下文環境,但是理解成容器會更好些。  ApplicationContext則是應用的容器。 Spring把Bean(object)放在容器中,需要用就通過get方法取出來。 ApplicationEven