spring boot之SpringApplication 事件监听

网友投稿 259 2023-01-11


spring boot之SpringApplication 事件监听

spring application listener

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

事件类型

EventType

发布时间

jAHyDqL ApplicationContextInitializedEvent

在 SpringApplication正在启动, ApplicationContext 已经准备好了,ApplicationContextInitializers 被调用, bean definitions 被加载之前

ApplicationStartingEvent

在一次启动之前发布

ApplicationEnvironmentPreparedEvent

在 Environment 准备好之后,会有 context 去使用这一 Environment, 会在 context 创建之前发出

ApplicationPreparedEvent

会在 bean definitions 加载之后,refresh 之前发布

ApplicationStartedEvent

context 更新之后,任何应用或命令行启动调用之前

ApplicationReadyEvent

任何应用或命令行启动调用之后发布,说明应用已经可以被请求了

ApplicationFailedEvent

启动发生有异常时发步

如何监听

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

@FunctionalInterface

public interface ApplicationListener 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 {

@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)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:状态转换图和接口测试(状态转换图和接口测试的区别)
下一篇:微服务网关如何调用服务(微服务架构中服务网关的作用)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~