spring中对Observer设计模式的支持

相信如果大家做过Win32下的开发,一定对用户自定义用户事件比较熟悉。在spring中ApplicationContext的时间处理是通过ApplicationEvent 类和ApplicationListener接口实现的。当在你的beans中执行了ApplicationListener,每次一个 ApplicationEvent 发布到ApplicationContext中,你的bean就会得到notified。这依赖于标准的, Observer设计模式。Spring提供三个标准的events:
ContextRefreshedEvent当ApplicationContext 初始化或刷新的时候,激发此事件。初始化意思是全部的被加载, singletons被预先实例化,并且 ApplicationContext可以被使用。
ContextClosedEvent当ApplicationContext关闭时激发此事件。即 singletons被释放。
RequestHandledEvent一个基于web的event,告诉所有的beans 一个HTTP 请求被服务。
(以上翻译自Spring Reference 3.10.2)
在Spring中提供了一个例子,我尝试了一下,还是比较让人感觉舒服的。
ApplicationContext定义:
[code:1]<bean id="emailer" class="example.EmailBean">
<property name="blackList">
<list>
<value>black@list.org</value>
<value>white@list.org</value>
<value>john@doe.org</value>
</list>
</property>
</bean>
<bean id="blackListListener" class="example.BlackListNotifier">
<property name="notificationAddress">
<value>spam@list.org</value>
</property>
</bean>[/code:1]
实际的bean代码如下:
[code:1]public class EmailBean implements ApplicationContextAware {
/** the blacklist */
private List blackList;
public void setBlackList(List blackList) {
this.blackList = blackList;
}
public void setApplicationContext(ApplicationContext ctx) {
this.ctx = ctx;
}
public void sendEmail(String address, String text) {
if (blackList.contains(address)) {
BlackListEvent evt = new BlackListEvent(address, text);
ctx.publishEvent(evt);
return;
}
// send email
}
}
public class BlackListNotifier implement ApplicationListener {
/** notification address */
private String notificationAddress;
public void setNotificationAddress(String notificationAddress) {
this.notificationAddress = notificationAddress;
}
public void onApplicationEvent(ApplicationEvent evt) {
if (evt instanceof BlackListEvent) {
// notify appropriate person[/code:1]
文中并没有给出BlackListEvent的代码,我自己实现如下:
[code:1]public class BlackListEvent extends ApplicationEvent{
    public BlackListEvent(Object o) {
        super(o);
    }
}[/code:1]
你可以自己通过执行ApplicationListener接口扩充新的类。体验一下spring带给你的方便。
另外,我在查看spring的帮助时候,发现一个新的类(SpringReference中没有提到),就是ConfigurableApplicationContext,它扩展了ApplicationContext类,并提供Close()和Refresh()方法。也就是说你自己可以触发ContextClosedEvent事件和ContextRefreshedEvent事件,不过我发现在调用close()方法的时候,ApplicationContext没有关闭,行为却是更新。