spring boot学习(3): SpringApplication 事件监听

spring application listener

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

事件类型

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

如何监听

  1. 监听器需要使用 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);
}
  1. 需要使用 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值