spring 的事件发布以及监听器

本文详细介绍了观察者模式的概念及其在Spring框架中的实现方式。通过发布者、事件对象和监听器三个核心组件,展示了如何利用Spring提供的接口实现一个简单的观察者模式实例。

 观察者模式是对象的行为模式,又叫发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。

  观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。想要实现观察者模式,个人觉得需要三部分1:发布者,2.发布的事件,3.监听器。发布者见名之意,就是当程序发生变化,由发布者发布事件;发布的事件就是发布者要发布信息内容;监听器就是接受发布者发布的事件;然而强大的spring提供这样的几个接口,ApplicationEventPulisherAware,实现该接口的类相当于拥有了发布这个方法,即可理解为实现该接口的类是发布者;另外一个就是ApplicationEvent,是一个抽象类,继承该类重写了构造方法,实现该类必须重写构造方法,可将事件的内容封装在该对象的 protected transient Object  source中(如有兴趣了解代码);最后一个接口就是ApplicationListener<ApplicationEvent>,同理,该接口提供监听的方法,所以实现该接口的类都拥有该行为;下面贴上一个简单的dome;

发布者:

package com.yu.listener;


import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;


@Component
public class TestPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}

public void publishEvent(TestEvent testEvent){
applicationEventPublisher.publishEvent(testEvent);
}
};

事件对象:

package com.yu.listener;


import org.springframework.context.ApplicationEvent;


public class TestEvent extends ApplicationEvent {


/**

*/
private static final long serialVersionUID = 1L;


public TestEvent(Object source) {
super(source);
// TODO Auto-generated constructor stub
}


}

监听器对象:

package com.yu.listener;


import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;




@Component
public class TestEventListener implements ApplicationListener<TestEvent>,Runnable{
private TestEvent event;


@Override
public void onApplicationEvent(TestEvent event) {
System.out.println(this);
// TODO Auto-generated method stub
TestEvent testEvent = (TestEvent)event;
this.event = testEvent; 
Thread t1 = new Thread(this);
System.out.println("进入了监听器方法!");
t1.start();
}


@Override
public void run() {
System.out.println(this);
// TODO Auto-generated method stub
System.out.println("进入了线程的run方法!");
System.out.println(this.event);
}


};


在这里有个地方主要的是,创建线程要使用this对象。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值