天天看点

spring 事件监听器(ApplicationEvent与ApplicationListener)

什么是ApplicationContext? 

它是spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。 

ApplicationContext则是应用的容器。

Spring把Bean(object)放在容器中,需要用就通过get方法取出来。

spring 事件为bean 与 bean之间传递消息。一个bean处理完了希望其余一个接着处理.这时我们就需要其余的一个bean监听当前bean所发送的事件.

spring事件使用步骤如下:

1.先自定义事件:你的事件需要继承 ApplicationEvent

2.定义事件监听器: 需要实现 ApplicationListener

3.使用容器对事件进行发布

一、先定义事件(我这里随便定义了一个实体类大家可自行定义):

import org.springframework.context.ApplicationEvent;

public class PersonEvent extends ApplicationEvent {

     private static final long serialVersionUID = 1L;

     public String text;

     public PersonEvent(Object source) {

         super(source);

     }

     public PersonEvent(Object source, String text) {

         super(source);

         this.text = text;

     }

     public void print(){

         System.out.println("hello spring event!");

     }

    public String getText() {

        return text;

    }

}

二、然后定义事件监听器(我这里用了两种方法,一种是使用注解   、 另一种是实现ApplicationListener):

import org.springframework.context.ApplicationEvent;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.EventListener;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Component;

@Component

public class PersonListenner implements ApplicationListener<PersonEvent>{

//public class PersonListenner {

    // 注释的代码为方法一

//    @EventListener

//    public void print(PersonEvent personEvent) {

//        System.out.println("打印信息="+personEvent.getText());

//    }

    // 方法二

    //使用注解@Async支持 这样不仅可以支持通过调用,也支持异步调用,非常的灵活,

    @Async

    @Override

    public void onApplicationEvent(PersonEvent personEvent) {

        // TODO Auto-generated method stub

        System.err.println("打印信息="+personEvent.getText());

    }

}

三、发布事件:

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.stereotype.Service;

@Service

public class PerService {

    @Autowired

    ApplicationContext applicationContext;

    public void getListener() {

        //发布PersonEvent事件

        applicationContext.publishEvent(new PersonEvent("Hello", "我是好人!"));

    }

}

四、调用(在需要的地方调用PerService类即可)

在需要的地方使用@Autowired注解即可调用
spring 事件监听器(ApplicationEvent与ApplicationListener)

所谓的知识技术都是一点点积累过来的,有一句话叫做 “不积跬步无以至千里”。

继续阅读