Spring ApplicationContext事件机制

ApplicationContext是观察者模式的实现。

ApplicationEvent--事件容器

ApplicationListener--事件监听器(onApplicationEvent(ApplicationEvent event) )


import org.springframework.context.ApplicationEvent;

public class EmailEvent extends <strong style="background-color: rgb(102, 255, 153);">ApplicationEvent</strong> {

	private static final long serialVersionUID = 1L;

	private String address;
	private String text;

	public EmailEvent(Object source) {
		super(source);
	}
	
	public EmailEvent(Object source,String address,String text){
		super(source);
		this.setAddress(address);
		this.setText(text);
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

}


public class EmailNotifier <strong style="background-color: rgb(102, 255, 153);">implements ApplicationListener</strong> {

	// 该方法会在容器发生事件时自动触发
	@Override
	public void <span style="background-color: rgb(153, 255, 255);"><strong>onApplicationEvent</strong></span>(ApplicationEvent event) {

		if (event instanceof EmailEvent) {
			// 只处理EmailEvent,发送email通知。。。。
			EmailEvent emailEvent = (EmailEvent) event;
			System.out.println("需要发送邮件的接收地址 " + emailEvent.getAddress());
			System.out.println("需要发送邮件的邮件正文" + emailEvent.getText());
		} else {
			// 容器内置事件不作任何处理
			System.out.println("容器本身的事件: " + event);
		}
	}

}


bean.xml
<strong style="background-color: rgb(51, 255, 255);"><!-- 配置监听器 -->
<bean class="com.cnpc.spring.listener.EmailNotifier"/></strong>

@Test
	// ApplicationContext的事件机制
	public void testEvent() { // 需要aop
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "bean.xml" });

		EmailEvent event = new EmailEvent("", "aups@163.com",
				"this is a test email");
		// 主动触发容器事件
		<span style="background-color: rgb(51, 255, 255);"><strong>context.publishEvent(event);</strong></span>
	}



容器本身的事件: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@73844508: startup date [Tue Feb 03 13:31:17 CST 2015]; root of context hierarchy]
需要发送邮件的接收地址 apus@163.com

需要发送邮件的邮件正文this is a test email.

监听器不仅监听到程序所触发的事件,也监听到容器内置的事件。实际上,如果开发者需要在Spring容器初始化,销毁时回调自定义方法,就可以通过上面的事件监听器来实现。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值