SpringBoot中如何实现加载应用事件监听器的代码示例?

2026-05-26 04:391阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计251个文字,预计阅读时间需要2分钟。

SpringBoot中如何实现加载应用事件监听器的代码示例?

利用Spring工厂加载机制,实例化ApplicationListener接口实现类,并对对象集合进行排序,创建应用事件监听器。创建类实现ApplicationListener接口,使用@Order或实现Ordered接口进行排序。

利用 Spring 工厂加载机制,实例化 ApplicationListener 实现类,并排序对象集合

创建应用事件监听器

创建类实现接口ApplicationListener,可以使用@Order或实现Orderd接口进行排序

@Order(Ordered.HIGHEST_PRECEDENCE) public class HelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("HelloWorld : " + event.getApplicationContext().getId() + " , timestamp : " + event.getTimestamp()); } }

public class AfterHelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent>,Ordered { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("AfterHelloWorld : " + event.getApplicationContext().getId() + " , timestamp : " + event.getTimestamp()); } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }

在spring.properties中配置

# ApplicationListener
org.springframework.context.ApplicationListener=\
com.imooc.diveinspringboot.listener.AfterHelloWorldApplicationListener,\
com.imooc.diveinspringboot.listener.HelloWorldApplicationListener,\

输出

HelloWorld : application , timestamp : 1591105193644
AfterHelloWorld : application , timestamp : 1591105193644

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

SpringBoot中如何实现加载应用事件监听器的代码示例?

本文共计251个文字,预计阅读时间需要2分钟。

SpringBoot中如何实现加载应用事件监听器的代码示例?

利用Spring工厂加载机制,实例化ApplicationListener接口实现类,并对对象集合进行排序,创建应用事件监听器。创建类实现ApplicationListener接口,使用@Order或实现Ordered接口进行排序。

利用 Spring 工厂加载机制,实例化 ApplicationListener 实现类,并排序对象集合

创建应用事件监听器

创建类实现接口ApplicationListener,可以使用@Order或实现Orderd接口进行排序

@Order(Ordered.HIGHEST_PRECEDENCE) public class HelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("HelloWorld : " + event.getApplicationContext().getId() + " , timestamp : " + event.getTimestamp()); } }

public class AfterHelloWorldApplicationListener implements ApplicationListener<ContextRefreshedEvent>,Ordered { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("AfterHelloWorld : " + event.getApplicationContext().getId() + " , timestamp : " + event.getTimestamp()); } @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }

在spring.properties中配置

# ApplicationListener
org.springframework.context.ApplicationListener=\
com.imooc.diveinspringboot.listener.AfterHelloWorldApplicationListener,\
com.imooc.diveinspringboot.listener.HelloWorldApplicationListener,\

输出

HelloWorld : application , timestamp : 1591105193644
AfterHelloWorld : application , timestamp : 1591105193644

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

SpringBoot中如何实现加载应用事件监听器的代码示例?