论坛首页 Java企业应用论坛

spring中对Observer设计模式的支持。

浏览 9994 次
该帖已经被评为精华帖
作者 正文
   发表时间:2004-05-25  
相信如果大家做过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定义:
<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>

实际的bean代码如下:
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

文中并没有给出BlackListEvent的代码,我自己实现如下:
public class BlackListEvent extends ApplicationEvent{
    public BlackListEvent(Object o); {
        super(o);;
    }
}

你可以自己通过执行ApplicationListener接口扩充新的类。体验一下spring带给你的方便。
另外,我在查看spring的帮助时候,发现一个新的类(Spring Reference中没有提到),就是ConfigurableApplicationContext,它扩展了ApplicationContext类,并提供Close()和Refresh()方法。也就是说你自己可以触发ContextClosedEvent事件和ContextRefreshedEvent事件,不过我发现在调用close()方法的时候,ApplicationContext没有关闭,行为却是更新。好奇怪,还没弄清楚是怎么一回事情。 呵呵,希望高人可以给我指点一二!
   发表时间:2004-05-25  
能像作者这样研究spring这么深入的,很少。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics