一个Spring事件监听例子

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:向小狗 发送完一封邮件



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值