关于ApplicationListener的使用方式以及原理

关于ApplicationListener的使用方式以及原理

1.背景

我们都知道,当我们的项目是springboot项目时如果我们想在容器启动的时候做一些配置的加载或者其他的一些操作,我们可以使用@PostConstruct注解,但是我今天主要想深入的是ApplicationListener基于我们监听的事件完成我们想要做的一些操作。

2.实现事件监听的方式

2.1自定义类实现ApplicationListener接口

@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("spring事件刷新成功");
    }
}

上述代码实现了ApplicationListener这个接口,监听的事件是ContextRefreshEvent这个事件,当这个实现被分发的时候,我们自定义的这个监听器就会收到通知,然后调用我们自己的逻辑,这里只是做一个简单的示范,具体业务逻辑根据业务来控制。

2.2使用@EventListener注解来监听指定事件下面我们来看看代码

/**
 * @ClassName MyApplicationListenerWithAnnoation
 * @Description ApplicationListener使用注解
 * @Author ljm
 * @Date 21:59 2021/10/20
 * @Version 2.1
 **/
@Configuration
public class MyApplicationListenerWithAnnoation {

    @EventListener(classes = {ContextRefreshedEvent.class})
    protected void testEvent(){
        System.out.println("注解形式的事件刷新成功");
    }

}

我们在使用注解的时候可以通过设置监听指定的事件的字节码来实现监听那个事件,classess中可以存放多个事件类型。

3.如何实现监听自定义事件类型并完成监听

其实自定义事件并实现监听的话只要分三步就可以完成

3.1自定义事件类型继承ApplicationEvent

/**
 * @ClassName MyApplicationEvent
 * @Description 自定义事件类型
 * @Author ljm
 * @Date 21:58 2021/10/21
 * @Version 2.1
 **/
public class MyApplicationEvent extends ApplicationEvent {

    public MyApplicationEvent(Object source) {
        super(source);
    }

    public  void printEventMessage(String message){
        System.out.println("监听到的事件信息:"+message);
    }
}
3.2自定义Listenter并实现监听我们自己设置的事件

/**
 * @ClassName MyApplictionListener
 * @Description ApplicationListener测试
 * @Author ljm
 * @Date 21:53 2021/10/20
 * @Version 2.1
 **/
@Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {
    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        event.printEventMessage("自定义事件刷新成功");
        System.out.println("spring事件刷新成功");
    }
}
3.3最后一步就是将我们的事件通知出去
@SpringBootApplication
public class SpringkafkaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringkafkaApplication.class, args).publishEvent(new MyApplicationEvent(new Object()));
    }

}

其中publishEvent是将事件通知出去,相当于发一条消息,然后另外有个方法监听道这个消息的一个标识拿来消费

4.原理

4.1首先我们先从事件的发布开始入手,我们一层一层的跟踪源码查看事件是如何发送出去的,其实很简单,跟踪源码我们发现代码最后来到了AbstractApplicationContext这个类中调用publishEvent这个方法,下面请看下面代码注释

protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
		Assert.notNull(event, "Event must not be null");

		// Decorate event as an ApplicationEvent if necessary
		ApplicationEvent applicationEvent;
       //1.判断是否属于ApplicationEvent
		if (event instanceof ApplicationEvent) {
			applicationEvent = (ApplicationEvent) event;
		}
		else {
			applicationEvent = new PayloadApplicationEvent<>(this, event);
			if (eventType == null) {
				eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
			}
		}

		// Multicast right now if possible - or lazily once the multicaster is initialized
		if (this.earlyApplicationEvents != null) {
			this.earlyApplicationEvents.add(applicationEvent);
		}
		else {
            //2.getAppliationEventMulticaster()方法主要是返回一个applicationEventMulticaster帮助发送事件
			getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
		}

		// Publish event via parent context as well...
		if (this.parent != null) {
			if (this.parent instanceof AbstractApplicationContext) {
				((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
			}
			else {
				this.parent.publishEvent(event);
			}
		}
	}

4.2进入到multicastEvent方法

public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
   ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
    //获得执行器
   Executor executor = getTaskExecutor();
    //获得容器中所有的监听器
   for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
       //如果执行器不为空则直接异步调用
      if (executor != null) {
         executor.execute(() -> invokeListener(listener, event));
      }
      else {
          //同步调用
         invokeListener(listener, event);
      }
   }
}
4.4最后其实调用的是doinvokeListener中的onApplicationEvent这个方法,这也表明了我们为何实现了ApplicationListener后要重写onApplicationEvent

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
   try {
      listener.onApplicationEvent(event);
   }
   catch (ClassCastException ex) {
      String msg = ex.getMessage();
      if (msg == null || matchesClassCastMessage(msg, event.getClass()) ||
            (event instanceof PayloadApplicationEvent &&
                  matchesClassCastMessage(msg, ((PayloadApplicationEvent) event).getPayload().getClass()))) {
         // Possibly a lambda-defined listener which we could not resolve the generic event type for
         // -> let's suppress the exception.
         Log loggerToUse = this.lazyLogger;
         if (loggerToUse == null) {
            loggerToUse = LogFactory.getLog(getClass());
            this.lazyLogger = loggerToUse;
         }
         if (loggerToUse.isTraceEnabled()) {
            loggerToUse.trace("Non-matching event type for listener: " + listener, ex);
         }
      }
      else {
         throw ex;
      }
   }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架的ApplicationListener是一个接口,用于监听Spring的上下文事件。它可以用于在Spring容器启动和关闭时执行一些特定的任务。下面是使用ApplicationListener的一些步骤: 1. 创建一个实现ApplicationListener接口的类,并实现onApplicationEvent()方法。该方法会在Spring上下文中发生事件时被触发。 2. 在Spring配置文件中注册这个监听器。可以通过添加<context:component-scan>和@Component注解来实现自动扫描,或者通过手动声明一个<bean>标签来注册。 3. 如果需要监听多个事件,可以在onApplicationEvent()方法中根据事件类型进行判断,然后执行相应的操作。 下面是一个简单的例子,演示了如何使用ApplicationListener监听Spring上下文的启动和关闭事件: ```java import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; public class MyListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { // Spring容器启动事件 System.out.println("Spring容器启动了!"); } else if (event instanceof ContextClosedEvent) { // Spring容器关闭事件 System.out.println("Spring容器关闭了!"); } } } ``` 在Spring配置文件中注册这个监听器: ```xml <bean id="myListener" class="com.example.MyListener"/> ``` 这样,当Spring容器启动或关闭时,就会调用MyListener类的onApplicationEvent()方法,并输出相应的信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值