spring事件處理

2021-09-01 19:37:47 字數 2601 閱讀 5860

spring中已經內建的幾種事件:

contextclosedevent   、contextrefreshedevent  、contextstartedevent  、contextstoppedevent   、requesthandleevent

首先自定義 2 種事件:

package com.tch.test.ssh.spring.event;

/** * 降價通知

* @author administrator

* */

private static final long serialversionuid = 1l;

public pricedecrease(object source)

public pricedecrease(string description)

}

package com.tch.test.ssh.spring.event;

/** * 漲價通知

* @author administrator

* */

private static final long serialversionuid = 1l;

public priceincrease(object source)

public priceincrease(string description)

}

然後定義***,並交給spring管理:

package com.tch.test.ssh.spring.listener;

import org.springframework.stereotype.component;

import com.tch.test.ssh.spring.event.pricedecrease;

import com.tch.test.ssh.spring.event.priceincrease;

/** * *****

* @author administrator

* */

@component

@override

if(event instanceof pricedecrease)else if(event instanceof priceincrease)

}}

接下來定義發布事件的元件(可以使用下面兩種方法之一):

package com.tch.test.ssh.spring.event;

import org.springframework.stereotype.component;

@component

@override

eventpublisher.eventpublisher = eventpublisher;

} system.out.println("eventpublisher發布了乙個事件");

eventpublisher.publishevent(event); }

}

package com.tch.test.ssh.spring.event;

import org.springframework.beans.bean***ception;

import org.springframework.stereotype.component;

@component

@override

throws bean***ception

system.out.println("通過globaleventpublisher發布了乙個事件");

context.publishevent(event); }

}

下面是spring的配置檔案:

<?xml version="1.0" encoding="utf-8"?>

最後測試:

package test;

import com.tch.test.ssh.spring.event.eventpublisher;

import com.tch.test.ssh.spring.event.globaleventpublisher;

import com.tch.test.ssh.spring.event.pricedecrease;

import com.tch.test.ssh.spring.event.priceincrease;

public class testspring

}

輸出結果:

eventpublisher發布了乙個事件

pricelistener監聽到pricedecrease事件:降價通知

通過globaleventpublisher發布了乙個事件

pricelistener監聽到priceincrease事件:漲價通知

spring 事件處理

private static final long serialversionuid 1l private string animalname public string getanimalname public animalspeakevent object source public anima...

Spring的Event事件處理使用詳解

spring中使用事件非常簡單,只需要以下的幾個步驟 public class userregisterevent extends public string getusername 定義傳送郵件和發放優惠券的監聽 component order 2 可以使用order指定順序,越小優先順序越高 p...

spring 事件監聽

用乙個簡單的例子來實現spring事件監聽的功能 這個例子主要功能是,記錄那些使用者是第一次登入系統,如果使用者是第一次登入系統,則呼叫spring的事件監聽,記錄這些使用者。主要用到的spring的類和介面有 這兩者構成了觀察者模式 observer 下面讓我們來看下實現 private stri...