ApplicationEvent和ApplicationListener的使用

spring的事件(ApplicationEvent)为bean和bean之间的消息通信提供了支持。当bean处理完一个事件之后,希望另一个bean能够知道并做相应的处理。这时另一个bean监听当前bean所发送的事件。
spring的事件流程如下:

  1. 自己的event需要继承 ApplicationEvent,并且写相应的构造函数
  2. 定义一个监听器listener,实现ApplicationListener接口,重写onApplicationEvent方法
  3. 使用ApplicationContext容器发布事件

代码如下:

1.创建一个DemoEvent

package com.xingguo.logistics.service.event;

import org.springframework.context.ApplicationEvent;

public class DemoEvent extends ApplicationEvent{
    private static final long serialVersionUID = 1L;

    private String message;

    public DemoEvent(Object source,String message){
        super(source);
        this.message = message;
    }

    public String getMessage() {
         return message;
          }

    }

2.创建一个监听DemoListener

package com.xingguo.logistics.service.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

//实现ApplicationListener接口,指定监听的事件类型DemoEvent
@Component
public class DemoListener implements ApplicationListener<DemoEvent>{

    //使用onApplicationEvent接收消息
    @Override
    public void onApplicationEvent(DemoEvent event) {
        String msg = event.getMessage();
        System.out.println("接收到的信息:"+msg);
    }

}

3.创建一个配置类(注意这里使用的是spring4.x)

package com.xingguo.logistics.controller;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan({"com.xingguo.logistics.service.event"})
public class AopConfig {

}

4.事件发布

package com.xingguo.logistics.service.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoPublisher {
    //容器注入
    @Autowired
    ApplicationContext applicationContext;

    public void publish(String message){
        //发布事件
        applicationContext.publishEvent(new DemoEvent(this, message));
    }
}

5.测试:

package com.xingguo.logistics.controller;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.xingguo.logistics.service.event.DemoPublisher;

public class TestController {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);

        DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
        demoPublisher.publish("发布消息");
        context.close();

    }
}

测试结果如下:
这里写图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值