spring boot中怎么使用SpringApplication实现事件监听

发布时间:2021-06-11 15:31:56 作者:Leah
来源:亿速云 阅读:125

spring boot中怎么使用SpringApplication实现事件监听,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

spring application listener

在 spring 框架中,有多种事件, 这些时间会在不同的运行时刻发布,来通知监听者。本文仅仅介绍 SpringApplicationEvent 的事件的监听。

事件类型

EventType发布时间
ApplicationContextInitializedEvent在 SpringApplication正在启动, ApplicationContext 已经准备好了,ApplicationContextInitializers 被调用, bean definitions 被加载之前
ApplicationStartingEvent在一次启动之前发布
ApplicationEnvironmentPreparedEvent在 Environment 准备好之后,会有 context 去使用这一 Environment, 会在 context 创建之前发出
ApplicationPreparedEvent会在 bean definitions 加载之后,refresh 之前发布
ApplicationStartedEventcontext 更新之后,任何应用或命令行启动调用之前
ApplicationReadyEvent任何应用或命令行启动调用之后发布,说明应用已经可以被请求了
ApplicationFailedEvent启动发生有异常时发步

如何监听

监听器需要使用 org.springframework.context.ApplicationListener 这个接口的实例, 其声明如下:

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  /**
  * Handle an application event. * @param event the event to respond to
  */ 
 void onApplicationEvent(E event);
}

需要使用 SpringApplication.addListeners(…) 或 SpringApplicationBuilder.listeners(…) 来添加监听器。也可以在 META-INF/spring.factories 文件中配置:org.springframework.context.ApplicationListener=com.example.project.MyListener。

例子:

public class StartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
 @Override
 public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
  System.out.println("called own starting listener");

  System.out.println(applicationStartingEvent.getClass());
 }
}
@SpringBootApplication
public class DemoApplication {
 public static void main(String[] args){
  SpringApplication application = new SpringApplication(DemoApplication.class);
  application.addListeners(new StartingEventListener());
  application.run(args);
 }
}

终端运行 jar 包:

$ java -jar build/libs/springlisteners-0.0.1-SNAPSHOT.jar
called own starting listener
class org.springframework.boot.context.event.ApplicationStartingEvent

 .  ____     _      __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::    (v2.1.3.RELEASE)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 3步轻松搞定Spring Boot缓存
  2. Spring Boot中怎么集成Ehcache缓存

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring application

上一篇:JavaScript开发人员需要了解的简写技巧有哪些

下一篇:Java中ArrayList类的作用是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》