spring---ApplicationListener,ApplicationEvent

(残梦追月原创,转载注明)

    如果仅仅使用Spring的内定事件,那显然是远远不够的,幸好,Spring为我们提供了中自定义发布事件的能力。下面通过例程来展示如何发布并监听自定义的事件。

在工程中,我们定义一个Animal类,为受管Bean,它具有一个Speak方法,我们要做的就是监视该方法,当用户调用该方法时触发AnimalSpeakEvent事件。具体操作如下:

新建名字为IoC_Test3.9的java工程,添加Spring开发能力后,建立ioc.test包。新建一个事件类AnimalSpeakEvent,它继承自ApplicationEvent,重载其默认的构造方法。再添加一个String成员animalName和它的Geter方法。添加一个构造方法,此方法有两个参数,一个为source,一个为animalName。代码如下:

 1  package  ioc.test;
 2 
 3  import  org.springframework.context.ApplicationEvent;
 4 
 5  public   class  AnimalSpeakEvent  extends  ApplicationEvent {
 6 
 7       private   static   final   long  serialVersionUID  =   1L ;
 8 
 9       private  String animalName;
10 
11       public  AnimalSpeakEvent(Object source) {
12           super (source);
13      }
14 
15       public  AnimalSpeakEvent(Object source,String animalName) {
16           super (source);
17           this .animalName  =  animalName;
18      }
19 
20       public  String getAnimalName() {
21           return  animalName;
22      }
23 
24  }
25 

创建好该事件类后,就应该把它再合适的时候发布出去。既然它时一个“动物讲话事件”,那么就应该再动物“讲话”的时候发布,如何发布呢?我们知道要发布一个事件,就必须要调用ApplicationContextpublishEvent方法。要在Animal类中获得ApplicationContext的实例,就要实现ApplicationContextAware接口,代码如下:

 

 1  package  ioc.test;
 2 
 3  // import省略
 4 
 5  public   class  Animal  implements  ApplicationContextAware {
 6 
 7       private  ApplicationContext ac;
 8 
 9       private  String name;
10 
11       private   int  age;
12 
13       public  String speak(){
14 
15           ac.publishEvent( new  AnimalSpeakEvent( this , this .name));
16           return   "  我的名字是; " + this .name + " ,我的年龄是: " + this .age;
17     }
18 
19 
20      public   void  setApplicationContext(ApplicationContext arg0)  throws  BeansException {
21       this .ac  =  arg0;
22     }
23 
24  // Getet和Seter省略
25 
26  }
27 

到目前为之,我们已经在Animal类中把事件发布出去了,现在要监听该事件的发生了,至于监听方法,前面已经演示过,直接上代码:

 

 

 1  ackage ioc.test;
 2 
 3  import  org.springframework.context.ApplicationEvent;
 4  import  org.springframework.context.ApplicationListener;
 5 
 6  public   class  AnimalEventListener  implements  ApplicationListener {
 7 
 8       public   void  onApplicationEvent(ApplicationEvent event) {
 9           if  (event  instanceof  AnimalSpeakEvent) {
10              AnimalSpeakEvent a  =  (AnimalSpeakEvent) event;
11                  System.out.println( " 事件监听器 "   +   this .getClass().getSimpleName() + " :有一个动物在讲话!它的名字是: " +  a.getAnimalName());
12          }
13      }
14  }
15 

配置好Bean,为AnimalBean注入值,配置文件如下:

 

 

 

 1  <? xml version="1.0" encoding="UTF-8" ?>
 2  < beans   ………… >
 3 
 4       < bean  id ="Listener"  class ="ioc.test.AnimalEventListener"   />
 5 
 6       < bean  id ="Animal"  class ="ioc.test.Animal" >
 7         < property  name ="name"  value ="老虎"   />
 8         < property  name ="age"  value ="5"   />
 9       </ bean >
10 
11  </ beans >
12 

现在应该来测试一下了,看看我们的自定义的事件是不是会再动物“讲话”的时候发生,测试类TestMain代码如下: 

 

 

 1  package  ioc.test;
 2 
 3  import  org.springframework.context.support.AbstractApplicationContext;
 4  import  org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6  public   class  TestMain {
 7 
 8       public   static   void  main(String[] args) {
 9 
10          AbstractApplicationContext ac  =   new  ClassPathXmlApplicationContext(
11                   " applicationContext.xml " );
12 
13           // 从容器获取动物实例
14          Animal animal  =  (Animal)ac.getBean( " Animal " );
15 
16           // 让动物讲话
17          System.out.println(animal.speak());                
18      }
19  }
20 

运行该类中的主方法,输出结果如下: 


可以看到,再动物“讲话“之前,我们的事件监听器监听到“动物讲话”,并输出了讲话动物的名字。

 


ApplicationContextAware  

2008-11-23 20:26:01|  分类: spring资料|举报|字号 订阅

 Spring中提供一些Aware相关接口,像是BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,实作这些 Aware接口的Bean在被初始之后,可以取得一些相对应的资源,例如实作BeanFactoryAware的Bean在初始后,Spring容器将会注入BeanFactory的实例,而实作ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例等等。
 Bean取得BeanFactory、ApplicationContextAware的实例目的是什么,一般的目的就是要取得一些档案资源的存取、相 关讯息资源或是那些被注入的实例所提供的机制,例如ApplicationContextAware提供了publishEvent()方法,可以支持基于Observer模式的事件传播机制。
 ApplicationContextAware接口的定义如下:

ApplicationContextAware.java

public interface ApplicationContextAware {

    void setApplicationContext(ApplicationContext context);

}


 我们这边示范如何透过实作ApplicationContextAware注入ApplicationContext来实现事件传播,首先我们的HelloBean如下:

HelloBean.java

package onlyfun.caterpillar;

 

import org.springframework.context.*;

 

public class HelloBean implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    private String helloWord = "Hello!World!";

  

    public void setApplicationContext(ApplicationContext context) {

        this.applicationContext = context;

    }

  

    public void setHelloWord(String helloWord) {

        this.helloWord = helloWord;

    }

  

    public String getHelloWord() {

        applicationContext.publishEvent(

               new PropertyGettedEvent("[" + helloWord + "] is getted"));

        return helloWord;

    }

}


 ApplicationContext会由Spring容器注入,publishEvent()方法需要一个继承ApplicationEvent的对象,我们的PropertyGettedEvent继承了ApplicationEvent,如下:

PropertyGettedEvent.java

package onlyfun.caterpillar;

 

import org.springframework.context.*;

 

public class PropertyGettedEvent extends ApplicationEvent {

    public PropertyGettedEvent(Object source) {

        super(source);

    }

}


 当ApplicationContext执行publishEvent()后,会自动寻找实作ApplicationListener接口的对象并通知其发生对应事件,我们实作了PropertyGettedListener如下:

PrppertyGettedListener.java

package onlyfun.caterpillar;

 

import org.springframework.context.*;

 

public class PropertyGettedListener implements ApplicationListener {

    public void onApplicationEvent(ApplicationEvent event) {

        System.out.println(event.getSource().toString());  

    }

}


 Listener必须被实例化,这我们可以在Bean定义档中加以定义:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    <bean id="propertyGetterListener" class="onlyfun.caterpillar.PropertyGettedListener"/>

 

    <bean id="helloBean" class="onlyfun.caterpillar.HelloBean">

        <property name="helloWord"><value>Hello!Justin!</value></property>

    </bean>

</beans>


 我们写一个测试程序来测测事件传播的运行:

Test.java

package onlyfun.caterpillar;

 

import org.springframework.context.*;

import org.springframework.context.support.*;

 

public class Test {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

      

        HelloBean hello = (HelloBean) context.getBean("helloBean");

        System.out.println(hello.getHelloWord());

    }

}


 执行结果会如下所示:

log4j:WARN No appenders could be found for logger

(org.springframework.beans.factory.xml.XmlBeanDefinitionReader).

log4j:WARN Please initialize the log4j system properly.

org.springframework.context.support.ClassPathXmlApplicationContext:

displayName=[org.springframework.context.support.ClassPathXmlApplicationContext;

hashCode=33219526]; startup date=[Fri Oct 29 10:56:35 CST 2004];

root of ApplicationContext hierarchy

[Hello!Justin!] is getted

Hello!Justin!


 以上是以实作事件传播来看看实作Aware接口取得对应对象后,可以进行的动作,同样的,您也可以实作ResourceLoaderAware接口:

ResourceLoaderAware.java

public interface ResourceLoaderAware {

    void setResourceLoader(ResourceLoader loader);

}


 实作ResourceLoader的Bean就可以取得ResourceLoader的实例,如此就可以使用它的getResource()方法,这对于必须存取档案资源的Bean相当有用。
 基本上,Spring虽然提供了这些Aware相关接口,然而Bean上若实现了这些界面,就算是与Spring发生了依赖,从另一个角度来看,虽然您可以直接在Bean上实现这些接口,但您也可以透过setter来完成依赖注入,例如:

HelloBean.java

package onlyfun.caterpillar;

 

import org.springframework.context.*;

 

public class HelloBean {

    private ApplicationContext applicationContext;

    private String helloWord = "Hello!World!";

  

    public void setApplicationContext(ApplicationContext context) {

        this.applicationContext = context;

    }

  

    public void setHelloWord(String helloWord) {

        this.helloWord = helloWord;

    }

  

    public String getHelloWord() {

        applicationContext.publishEvent(new PropertyGettedEvent("[" + helloWord + "] is getted"));

        return helloWord;

    }

}


 注意这次我们并没有实作ApplicationContextAware,我们在程序中可以自行注入ApplicationContext实例:

ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

      

HelloBean hello = (HelloBean) context.getBean("helloBean");

hello.setApplicationContext(context);

System.out.println(hello.getHelloWord());


 就Bean而言,降低了对Spring的依赖,可以比较容易从现有的框架中脱离。








评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值