當把一個事件發布到spring提供的applicationcontext中,被監聽器偵測到,就會執行對應的處理方法。
事件本身
事件是一個自定義的類,需要繼承spring提供的applicationevent
。
1
2
3
4
5
6
7
8
9
|
@data public class myevent extends applicationevent { private string msg; public myevent(object source, string msg) { super (source); this .msg = msg; } } |
事件監聽
基本方法是實現applicationlistener
接口,自定義一個監聽器,實現onapplicationevent()
方法,然后添加到applicationcontext
。
比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public class mylistener implements applicationlistener<myevent> { @override public void onapplicationevent(myevent event) { system.out.print( "監聽到myevent事件" ); } } ... // springboot的啟動類中添加監聽器 public static void main(string[] args) { springapplication application = new springapplication(myapplication. class ); application.addlisteners( new mylistener()); application.run(args); } |
也可以使用注解@eventlistener
(推薦):原理就是通過掃描這個注解,創建監聽器并添加到applicationcontext
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@component @slf4j public class myeventhandler { @eventlistener public void handleevent(myevent event) { log.info( "------------處理事件:{}" , event.getmsg()); try { thread.sleep( 5 * 1000l); log.info( "事件1(5s)處理完成" ); } catch (interruptedexception e) { e.printstacktrace(); } } } |
事件發布
可以通過上下文對象的發布方法configurableapplicationcontext::publishevent()
來發布。
也可以實現applicationeventpublisheraware
接口來發布(推薦)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@component @slf4j public class eventservice implements applicationeventpublisheraware { public applicationeventpublisher publisher; @override public void setapplicationeventpublisher(applicationeventpublisher applicationeventpublisher) { this .publisher = applicationeventpublisher; } public string doeventwork(string msg) { log.info( "------------publish event:" + msg); myevent event = new myevent( this , msg); publisher.publishevent(event); return "ok" ; } } |
測試代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
@springboottest @runwith (springrunner. class ) public class eventservicetest { @autowired private eventservice service; @test public void eventtest() { string msg= "java code" ; service.doeventwork(msg); } } |
注意
如果2個事件之間是繼承關系,會先監聽到子類事件,處理完再監聽父類。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
// myevent2 extends myevent @component @slf4j public class myeventhandler { @eventlistener public void handleevent(myevent event) { log.info( "------------處理事件:{}" , event.getmsg()); try { thread.sleep( 5 * 1000l); log.info( "事件1(5s)處理完成" ); } catch (interruptedexception e) { e.printstacktrace(); } } @eventlistener public void handleevent2(myevent2 event) { log.info( "------------處理事件2:{}" , event.getmsg()); try { thread.sleep( 10 * 1000l); log.info( "事件2(10s)處理完成" ); } catch (interruptedexception e) { e.printstacktrace(); } } } |
當我publish一個子類事件myevent2時,日志如下:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/47ae0bbdf205