当把一个事件发布到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