Spring 的 ApplicationContext 除了管理 Bean,還內建了一套事件傳播機制。它讓「發生了什麼事」與「事後要做什麼」彼此脫鉤,是解耦的一把好工具。
主角是 publishEvent() 方法:呼叫它把事件散播出去,容器會把它交給所有感興趣的監聽器(需實作 ApplicationListener 介面)。
ApplicationContext 並非直接繼承 BeanFactory,其中與事件相關的關鍵是 ApplicationEventPublisher 介面——翻開原始碼會發現它只有一個方法:
void publishEvent(ApplicationEvent event);
此外 Spring 提供了一系列 Aware 介面,最常用的是 ApplicationContextAware、ResourceLoaderAware、ServletContextAware(注意 Struts2 也有同名介面,別混淆)。凡是實作了 ApplicationContextAware 的 Bean,在初始化階段都會被注入 ApplicationContext 實例。
事件必須繼承 Spring 提供的 ApplicationEvent。
package net.wang.test;
import org.springframework.context.ApplicationEvent;
public class TradeEvent extends ApplicationEvent {
public TradeEvent(Object source) {
super(source);
System.out.println("事件:TradeEvent event !!");
}
}
package net.wang.test;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
public class HelloWorld implements ApplicationEventPublisherAware {
private String word;
private ApplicationEventPublisher tradeEventPublisher;
public void setWord(String word) {
this.word = word;
}
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.tradeEventPublisher = publisher;
}
public void say() {
System.out.println("say:" + this.word);
TradeEvent tradeEvent = new TradeEvent(new String("HelloWorld!"));
this.tradeEventPublisher.publishEvent(tradeEvent);
}
}
事件在 say() 方法中被發出。
接收者其實就是監聽器,實作 ApplicationListener 並把事件型別寫進泛型。
package net.wang.test;
import org.springframework.context.ApplicationListener;
public class EventReceiver implements ApplicationListener<TradeEvent> {
public void onApplicationEvent(TradeEvent event) {
System.out.println("監聽到的事件:" + event.getSource());
}
}
<?xml version="1.0" encoding="GBK"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean name="helloWrold" class="net.wang.test.HelloWorld">
<property name="word" value="Word!"/>
</bean>
<bean name="eventReceiver" class="net.wang.test.EventReceiver"/>
</beans>
別忘了把監聽器也註冊進容器,否則事件發出去沒有接收方。
package net.wang.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld h = (HelloWorld) ctx.getBean("helloWrold");
h.say();
}
}
事件機制適合那種「A 做完之後,B、C、D 各自要做點事,但 A 不該知道 B、C、D 存在」的場合,例如寄信、寫日誌、更新快取。反過來說,如果流程是嚴格線性的業務步驟,直接呼叫反而更清楚——事件發布是同步的,出錯時堆疊追蹤也會變得不好讀,這是使用前必須權衡的代價。