快捷搜索:  as  test  1111  test aNd 8=8  test++aNd+8=8  as++aNd+8=8  as aNd 8=8

葡京赌场网站多少:Spring中事件处理的小技巧



Spring中供给一些Aware相关的接口,BeanFactoryAware、 ApplicationCo葡京赌场网站多少ntextAware、ResourceLoaderAware、ServletContextAware等等,此中最常用到的是ApplicationContextAware。实现ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例。Appli葡京赌场网站多少cationContextAware供给了publishEvent()措施,实现Observer(察看者)设计模式的事故传播机,供给了针对Bean的事故传播功能。经由过程Application.publishEvent措施,我们可以将事故看护系统内所有的ApplicationListener。

Spring事故处置惩罚一样平常历程:

·定义Event类,承袭org.springframework.context.ApplicationEvent.

·编写宣布事故类Publisher,实现org.springframework.context.ApplicationContextAware接口.

·覆盖措施setApplicationContext(ApplicationContext applicationContext)和宣布措施publish(Object obj)

·定义光阴 监听类EventListener,实现ApplicationListener接口,实现措施onApplicationEvent(ApplicationEvent event).

java 代码

import org.springframework.co葡京赌场网站多少ntext.ApplicationEvent;

/**

* 定义事故信息

* @author new

*

*/

public class MessageEvent extends ApplicationEvent {

private String message;

public void setMessage(String message){

this.message = message;

}

public String getMessage(){

return message;

}

public MessageEvent(Object source, String message) {

super(source);

this.message = message;

// TODO Auto-generated c葡京赌场网站多少onstructor stub

}

private static final long serialVersionUID = 1L;

}

java 代码

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Publisher implements ApplicationContextAware {

private ApplicationContext context;

@Override

public void setApplicationContext(ApplicationContext arg0)

throws BeansException {

// TODO Auto-generated method stub

this.context = arg0;

}

public void publish(String message){

context.publishEvent(new MessageEvent(this,message));

}

public static void main(String[] args) {

ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");

Publisher pub = (Publisher) ctx.getBean("publisher");

pub.publish("Hello World!");

pub.publish("The quick brown fox jumped over the lazy dog");

}

}

java 代码

import org.springframework.context.ApplicationEvent;

import org.springframework.context.ApplicationListener;

public class MessageEventListener implements ApplicationListener {

@Override

public void onApplicationEvent(ApplicationEvent event) {

// TODO Auto-generated method stub

if(event instanceof MessageEvent){

MessageEvent msEvent = (MessageEvent)event;

System.out.print葡京赌场网站多少ln("Received: " + msEvent.getMessage());

}

}

}

在运行期,ApplicationContext会自动在当前的所有Bean中探求ApplicationListener接口的实现,并将其作为事故接管工具。当Application.publishEvent措施调用时,所有的ApplicationListener接口实现都邑被引发,每个ApplicationListener可根据事故的类型判断是否是自己必要处置惩罚的事故,如上面的ActionListener只处置惩罚ActionEvent事故。

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

您可能还会对下面的文章感兴趣: