Spring的事件(Application Event)为Bean与Bean之间的消息通信提供了支持。当一个 Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时需要让另外一个Bean监听当前Bean所发送的事件。
事件概念
事件相关角色:
- **事件:**具体的某些事。
- **事件源:**事件的产生者,任何一个事件都有一个事件源。
- **事件监听器:**监听具体的事件。
- **事件监听器注册表:**为事件监听器提供保存的组件或框架。当事件源产生事件时,就会通知这些位于事件监听器注册表中的监听器。
- **事件广播器:**负责把事件通知给监听器,是事件和监听器沟通的桥梁。
自定义ApplicationEvent
- 自定义事件,继承
ApplicationEvent
- 定义事件监听器,实现
ApplicationListener
- 使用容器发布事件。
自定义事件发布/监听示例
- 自定义事件
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 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;
@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 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 { @Autowired private ApplicationContext applicationContext; public void publish(String msg) { applicationContext.publishEvent(new Event(this, msg)); } }
|
- 配置类
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 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(); } }
|