Spring中的事件简述与Guava的EventBus

Spring的事件

关键类

  1. org.springframework.context.ApplicationEvent

  2. org.springframework.context.ApplicationListener

使用容器触发事件,applicationContext发布事件。

简单实现逻辑

  1. 自定义订阅和通知事件,继承ApplicationEvent

  2. 定义事件监听器,实现ApplicationListener

  3. 使用容器发布事件(订阅、通知)

拓展@EventListener注解

为了加强@EventListener的功能,Spring 4.2开始支持使用SpEL表达式定义事件触发的条件。

下面为使用了该注解的的一个实例:

Event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TestEvent extends ApplicationEvent {

public boolean isImport;

public TestEvent(Object source, boolean isImport) {
super(source);
this.isImport = isImport;
}

public boolean isImport() {
return isImport;
}

public void setImport(boolean anImport) {
isImport = anImport;
}

@Override
public String toString() {
return "TestEvent{" +
"isImport=" + isImport +
'}';
}
}

Listener:

1
2
3
4
5
6
7
8
9
@Component
public class EventHandler {

// 当isImport为true的时候才会打印
@EventListener(condition="#testEvent.isImport")
public void TestEventTest(TestEvent testEvent) {
System.out.println("==============TestEvent==============" + testEvent.toString());
}
}

拓展Google Guava中的EventBus

GoogleGuava是谷歌在日常开发过程中总结积累出来的一个类库,包含了许多常用的工具等。

Guava的优点:

  • 高效设计良好的API,被Google的开发者设计,实现和使用
  • 遵循高效的java语法实践
  • 使代码更刻度,简洁,简单
  • 节约时间,资源,提高生产力

Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:

  • 集合 [collections]
  • 缓存 [caching]
  • 原生类型支持 [primitives support]
  • 并发库 [concurrency libraries]
  • 通用注解 [common annotations]
  • 字符串处理 [string processing]
  • I/O 等等。

这里我们主要介绍Guava中的事件总线EventBus。使用Guava的事件总线就不用再像上面Spring中的继承实现接口的方法。只需要在指定的事件处理方法上加@Subscribe注解即可。

消息封装类:

1
2
3
4
5
6
7
8
9
10
public class TestEvent {
private final int message;
public TestEvent(int message) {
this.message = message;
System.out.println("event message:"+message);
}
public int getMessage() {
return message;
}
}

消息接收类:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class EventListener {
public int lastMessage = 0;

@Subscribe
public void listen(TestEvent event) {
lastMessage = event.getMessage();
System.out.println("Message:"+lastMessage);
}

public int getLastMessage() {
return lastMessage;
}
}

测试类及输出结果:

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
public class TestEventBus {
@Test
public void testReceiveEvent() throws Exception {

EventBus eventBus = new EventBus("test");
EventListener listener = new EventListener();

eventBus.register(listener);

eventBus.post(new TestEvent(200));
eventBus.post(new TestEvent(300));
eventBus.post(new TestEvent(400));

                            System.out.println("LastMessage:"+listener.getLastMessage());
}
}

//输出信息
event message:200
Message:200
event message:300
Message:300
event message:400
Message:400
LastMessage:400

以上即是EventBus的简单使用。

参考资料:

https://shimo.im/docs/z7ggA56biOAfAdht/read

https://www.cnblogs.com/peida/p/EventBus.html