1:事件类
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
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;
}
}
2:监听器
import org.springframework.context.ApplicationListener;
public class MailSendListener implements ApplicationListener<MailSendEvent> {
@Override
public void onApplicationEvent(MailSendEvent event) {
// TODO Auto-generated method stub
MailSendEvent mse=event;
System.out.println("MailSendListener:向"+mse.getTo()+" 发送完一封邮件");
}
}
3:发送邮件,事件广播
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MailSender implements ApplicationContextAware {
private ApplicationContext ctx;
//ApplicationContextAware接口方法,以便容器启动时注入容器实例
@Override
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {<pre name="code" class="java">ApplicationContext ctx=new ClassPathXmlApplicationContext("com/aitiny/event/beans.xml");
MailSender mailSender=(MailSender) ctx.getBean("mailSender");
mailSender.sendMail("小狗");
// TODO Auto-generated method stubthis.ctx=ctx;}public void sendMail(String to){System.out.println("MailSender:模拟发送邮件。。。");MailSendEvent mse=new MailSendEvent(this.ctx,to);//向容器中的所有事件监听器发送事件ctx.publishEvent(mse);}}
4:配置bean
<bean class="com.aitiny.event.MailSendListener"></bean>
<bean id="mailSender" class="com.aitiny.event.MailSender"></bean>
5:测试
ApplicationContext ctx=new ClassPathXmlApplicationContext("com/aitiny/event/beans.xml");
MailSender mailSender=(MailSender) ctx.getBean("mailSender");
mailSender.sendMail("小狗");
控制台输出:MailSender:模拟发送邮件。。。
MailSendListener:向小狗 发送完一封邮件