五个人在报社订阅了报纸。报社一旦有了新报纸,就派员工分别送到这五个人手里。在这个例子中,“报纸”就是事件,“报社”就是广播器,五个订阅者就是监听器。广播器收到事件,把事件传给监听器,监听器对事件做一些事情。这样的例子属于观察者模式。
public class MailSendEvent extends ApplicationContextEvent { private String to; public MailSendEvent(ApplicationContext source, String to) { super(source); this.to = to; } public String getTo() { return this.to; } }
public class MailSendListener implements ApplicationListener<MailSendEvent>{ public void onApplicationEvent(MailSendEvent event) { MailSendEvent mse = (MailSendEvent) event; System.out.println("MailSendListener:向" + mse.getTo() + "发送完一封邮件"); } }
public class MailSender implements ApplicationContextAware { private ApplicationContext ctx ; public void setApplicationContext(ApplicationContext ctx) throws BeansException { this.ctx = ctx; } public void sendMail(String to){ System.out.println("MailSender:模拟发送邮件..."); MailSendEvent mse = new MailSendEvent(this.ctx,to); ctx.publishEvent(mse); } }
<bean class="com.baobaotao.event.MailSendListener"/> <bean id="mailSender" class="com.baobaotao.event.MailSender"/>
public static void main(String[] args) { String resourceFile = "com/baobaotao/event/beans.xml"; ApplicationContext ctx = new ClassPathXmlApplicationContext(resourceFile); MailSender mailSender = ctx.getBean(MailSender.class); mailSender.sendMail("test mail."); System.out.println("done."); }