spring 事件机制


spring的事件机制采用了观察者设计模式。

关键点在于ApplicationContext的两个成员:ApplicationEvent ApplicationListenter。

很显然ApplicatonEvent是java事件在Spring中的实现,用户要自定义一个spring事件,只需要继承自ApplicatonEvent;而ApplicationListener则是一个监听器,用户的自定义监听器同样需要实现ApplicationListener接口,并重写onApplicationEvent(ApplicationEvent event)方法。

定义完事件和监听器后需要在spring中进行配置。很简单,就是将监听器配置为一个bean:<bean class="com.lincoln.spring.EmailListener"/>。

第三步,触发事件:直接调用ApplicationContext的publishEvent(event)方法。

实例如下:

1、定义一个event:

 

public class EmailEvent extends ApplicationContextEvent{
    public EmailEvent(ApplicationContext source){
        super(source);
    }
    
    private String address ;
    private String content ;
    public void setAddress(String address) {
        this.address = address;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getAddress() {
        return address;
    }
    public String getContent() {
        return content;
    }
}

 

2、定义一个listener

public class EventListener implements ApplicationListener{

    public void onApplicationEvent(ApplicationEvent event) {
        if( event instanceof EmailEvent ){
            EmailEvent ee = (EmailEvent)event ;
            System.out.println("the email's address is "+ee.getAddress()+
                    "\n content is "+ee.getContent());
        }
    }
    
}

 

3、配置文件

<bean id="eventListener" class="com.lincoln.event.EventListener" ></bean>

 

4、测试类:

public class TestEvent {
    @Test
    public void testEvent()
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/lincoln/event/event.xml");
        EmailEvent event = new EmailEvent(context);
        event.setAddress("licolnsPei@gmail.com");
        event.setContent("Hello,spring ; I will fuck you !");
        context.publishEvent(event);
    }
}

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM