springboot中使用ApplicationListener和ApplicationEvent /@EventListener监听事件


自定义一个事件类

public class OnRegistrationCompleteEvent extends ApplicationEvent {
    private final User user;
    public OnRegistrationCompleteEvent(final User user) {
        super(user);
        System.out.println("登录/注册了一个"+user.toString());
        this.user = user;
    }
    public User getUser() {
        return user;
    }
}

监听类:

@Component
public class EventListener implements ApplicationListener<OnRegistrationCompleteEvent> {
    @Override
    @NonNull
    public void onApplicationEvent(OnRegistrationCompleteEvent event) {
        //事件发生后回调的方法
        System.out.println("监听"+event.getUser().toString());
    }
}

事件发布者

在业务层中注入publisher

@Service
public class UserServiceImpl  implements IUserService {
@Autowired
    UserMapper userMapper;
@Autowired
private ApplicationEventPublisher publisher;

    public ResponseResult insert(User record) {
        userMapper.insert(record);
        publisher.publishEvent(new OnRegistrationCompleteEvent(record));
        return ResponseResult.success(record);
    }
    }

ApplicationEventPublisher是ApplicationContext的父接口之一。这接口的作用是:Interface that encapsulates event publication functionality.

功能就是发布事件,也就是把某个事件告诉的所有与这个事件相关的监听器。
  
现在插入一条数据进行测试:
在这里插入图片描述

如果删掉 publisher.publishEvent(new OnRegistrationCompleteEvent(record));这句话会发现事件并没有被监听

改用@EventListener注解:

修改上面的监听类,不再继承ApplicationListener

@Component

public class EmailSendListener  {

    @NonNull
    @EventListener(classes=OnRegistrationCompleteEvent.class)
    public void onApplicationEvent(OnRegistrationCompleteEvent event) {
        //事件发生后回调的方法
        System.out.println("监听"+event.getUser().toString());
    }
}

再次插入数据:
在这里插入图片描述
一样可以起到监听作用。

总结

目前结论:需要自定义事件,监听者,发布者。
监听者类需要加@component注解交由spring管理,可以选择继承ApplicationEvent 也可以加@EventListener注解的方式
发布者发布事件后所有监听器将能接收到信息,回调监听到以后的方法
基本上牵涉到事件(Event)方面的设计,就离不开观察者模式,ApplicationContext 的事件机制主要通过 ApplicationEvent 和 ApplicationListener 这两个接口来提供的,和 Java swing 中的事件机制一样。即当 ApplicationContext 中发布一个事件时,所有扩展了 ApplicationListener 的 Bean都将接受到这个事件,并进行相应的处理。

ApplicationContext 扩展了 ResourceLoader(资源加载器)接口,从而可以用来加载多个Resource,而 BeanFactory 是没有扩展 ResourceLoader

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值