spring(十)-ApplicationListener及自定义监听事件

一、ApplicationListener 事件监听器

1、实现接口方式

监听的必须是 ApplicationEvent 自身或其子类、子接口

  • 实现 ApplicationListener 接口
@Component
public class MyApplicationListener implements ApplicationListener {
   
	/**
     * 当前事件
     * @param event
     */
    public void onApplicationEvent(ApplicationEvent event) {
   
        System.out.println(event.getClass
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 中,您可以通过实现 ApplicationListener 接口来创建自定义监听器。ApplicationListener 接口有一个 onApplicationEvent() 方法,该方法在特定事件发生时调用。要监听具体的方法,您需要发布一个特定类型的事件,然后在自定义监听器的 onApplicationEvent() 方法中处理该事件。 下面是一个简单的示例,演示如何创建自定义监听器来监听方法的调用: ```java import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; public class CustomMethodCallEvent extends ApplicationEvent { private String methodName; public CustomMethodCallEvent(Object source, String methodName) { super(source); this.methodName = methodName; } public String getMethodName() { return methodName; } } public class CustomMethodCallListener implements ApplicationListener<CustomMethodCallEvent> { @Override public void onApplicationEvent(CustomMethodCallEvent event) { // 处理事件 System.out.println("Method " + event.getMethodName() + " was called."); } } ``` 然后,您可以在需要监听的方法中发布事件: ```java import org.springframework.context.ApplicationEventPublisher; public class SomeService { private final ApplicationEventPublisher eventPublisher; public SomeService(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void someMethod() { // 调用方法 eventPublisher.publishEvent(new CustomMethodCallEvent(this, "someMethod")); } } ``` 最后,在 Spring 配置中将自定义监听器注册为 Spring Bean 即可。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值