Spring 官方文档翻译如下 :
ApplicationContext 通过 ApplicationEvent 类和 ApplicationListener 接口进行事件处理。 如果将实现 ApplicationListener 接口的 bean 注入到上下文中,则每次使用 ApplicationContext 发布 ApplicationEvent 时,都会通知该 bean。 本质上,这是标准的观察者设计模式。
Spring的事件(Application Event)其实就是一个观察者设计模式,一个 Bean 处理完成任务后希望通知其它 Bean 或者说 一个Bean 想观察监听另一个Bean的行为。
Spring 事件只需要几步:
自定义事件,继承 ApplicationEvent
定义监听器,实现 ApplicationListener 或者通过 @EventListener 注解到方法上
定义发布者,通过 ApplicationEventPublisher
1.自定义事件
public class SayHelloEvent extends ApplicationEvent {
private String message;
public SayHelloEvent(String message) {
super(message);
}
}
2.定义监听器
1.实现 ApplicationListener
@Component
public class SayHelloEventListener implements ApplicationListener<SayHelloEvent> {
@Override
public void onApplicationEvent(SayHelloEvent sayHelloEvent) {
String message = (String) sayHelloEvent.getSource();
System.out.println(message);
}
}
2.@EventListener
@Component
public class MyEventListener {
@EventListener
public void sayHelloEvent(SayHelloEvent event){
String message = (String) event.getSource();
System.out.println("total listener");
System.out.println(message);
}
}
3.定义发布者
@Component
public class EventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEven(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
4.测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = NormalApplication.class)
public class EventTest {
@Autowired
private EventPublisher eventPublisher;
@Test
public void test(){
SayHelloEvent helloEvent = new SayHelloEvent("this is my sayHelloEvent");
eventPublisher.publishEven(helloEvent);
}
}