Spring(十六):Spring ApplicationEvent 事件监听/发布

Spring的事件(Application Event)为BeanBean之间的消息通信提供了支持。当一个 Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时需要让另外一个Bean监听当前Bean所发送的事件。

事件概念

事件相关角色:

  1. **事件:**具体的某些事。
  2. **事件源:**事件的产生者,任何一个事件都有一个事件源。
  3. **事件监听器:**监听具体的事件。
  4. **事件监听器注册表:**为事件监听器提供保存的组件或框架。当事件源产生事件时,就会通知这些位于事件监听器注册表中的监听器。
  5. **事件广播器:**负责把事件通知给监听器,是事件和监听器沟通的桥梁。

自定义ApplicationEvent

  1. 自定义事件,继承ApplicationEvent
  2. 定义事件监听器,实现ApplicationListener
  3. 使用容器发布事件。

自定义事件发布/监听示例

  1. 自定义事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import org.springframework.context.ApplicationEvent;

public class Event extends ApplicationEvent {

private static final long serialVersionUID = 3047811723576856075L;
private String msg;

public Event(Object source, String msg) {
super(source);
this.msg = msg;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}
  1. 定义事件监听器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
* 实现ApplicationListener接口,并提定监听的事件类型
* @author Rocky
*
*/
@Component
public class EventListener implements ApplicationListener<Event> {

/**
* 对消息进行接受处理
*/
@Override
public void onApplicationEvent(Event event) {
String msg = event.getMsg();

System.out.println("我 bean-EventListener 接收到 bean-Publisher发布的消息: " + msg);
}
}
  1. 创建事件发布类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class EventPublisher {

//注入ApplicationContext用来发布事件
@Autowired
private ApplicationContext applicationContext;

//调用发布方法
public void publish(String msg) {
applicationContext.publishEvent(new Event(this, msg));
}
}
  1. 配置类
1
2
3
4
5
6
7
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.spring.event")
public class EventConfig {
}
  1. 执行类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class EventMain {

public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(EventConfig.class);

EventPublisher eventPublisher = context.getBean(EventPublisher.class);
eventPublisher.publish("hello application event");

context.close();
}
}

Spring(十六):Spring ApplicationEvent 事件监听/发布

http://blog.gxitsky.com/2018/04/28/Spring-16-ApplicationEvent/

作者

光星

发布于

2018-04-28

更新于

2022-06-17

许可协议

评论