Spring 官方文檔翻譯如下 :
ApplicationContext 通過(guò) ApplicationEvent 類(lèi)和 ApplicationListener 接口進(jìn)行事件處理抢呆。 如果將實(shí)現(xiàn) ApplicationListener 接口的 bean 注入到上下文中涌献,則每次使用 ApplicationContext 發(fā)布 ApplicationEvent 時(shí)赁濒,都會(huì)通知該 bean。 本質(zhì)上躬它,這是標(biāo)準(zhǔn)的觀察者設(shè)計(jì)模式。
Spring的事件(Application Event)其實(shí)就是一個(gè)觀察者設(shè)計(jì)模式,一個(gè) Bean 處理完成任務(wù)后希望通知其它 Bean 或者說(shuō) 一個(gè)Bean 想觀察監(jiān)聽(tīng)另一個(gè)Bean的行為竣稽。
Spring 事件只需要幾步:
自定義事件,繼承 ApplicationEvent
定義監(jiān)聽(tīng)器霍弹,實(shí)現(xiàn) ApplicationListener 或者通過(guò) @EventListener 注解到方法上
定義發(fā)布者毫别,通過(guò) ApplicationEventPublisher
1.自定義事件
public class SayHelloEvent extends ApplicationEvent {
private String message;
public SayHelloEvent(String message) {
super(message);
}
}
2.定義監(jiān)聽(tīng)器
1.實(shí)現(xiàn) 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.定義發(fā)布者
@Component
public class EventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEven(ApplicationEvent event) {
applicationEventPublisher.publishEvent(event);
}
}
4.測(cè)試類(lèi)
@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);
}
}