您的位置:首页 > 编程语言 > Java开发

Spring容器事件

2015-12-15 13:36 435 查看

概念

基本概念

事件源:事件生产者

事件监听器注册表:事件监听器的容器。

事件广播器:负责把事件通知给事件监听器,它是事件和事件监听器的桥梁。

Spring事件类结构

事件类ApplicationEvent继承了Java标准库中的EventObject

监听器类ApplicationListener继承了Java标准库中的EventListener。

事件广播器接口ApplicationEventMulticaster

具体示例

这里模拟一个短信发送器MessageSender,监听器MessageListener将发送的消息值打印出来。

事件:

package exa.ydoing.event;
import org.springframework.context.ApplicationEvent;
public class MessageEvent extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String sms;

public MessageEvent(Object source, String sms) {
super(source);
this.sms = sms;
}
public String getSms() {
return sms;
}
public void setSms(String sms) {
this.sms = sms;
}
}


监听器:

package exa.ydoing.event;
import org.springframework.context.ApplicationListener;
public class MessageListener implements ApplicationListener<MessageEvent>{
@Override
public void onApplicationEvent(MessageEvent event) {
System.out.println("发送消息: " + event.getSms());
}
}


发送器

需要实现ApplicationContextAware;这样发送器才能获得ApplicationContext的引用,而ApplicationContext接口扩展了ApplicationEventPublisher接口,发送器才能调用的ApplicationEventPublisher接口的publishEvent方法

package exa.ydoing.event;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
public class MessageSender implements ApplicationContextAware{
private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

public void sendMessage(String sms){
ApplicationEvent event = new MessageEvent(this.applicationContext, sms);

//向监听器发送事件
applicationContext.publishEvent(event);
}
}


测试:

package exa.ydoing.event;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");

MessageSender sender = ctx.getBean("messageSender", MessageSender.class);
sender.sendMessage("hello, world");
}
}


Bean在ApplicationContext.xml的定义

只要Bean实现了ApplicationContextAware接口,Spring容器会自动注入当前的ApplicationContext实例:

<bean class="exa.ydoing.event.MessageListener"/>
<bean id="messageSender" class="exa.ydoing.event.MessageSender"/>


输出

发送消息: hello, message
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 事件