Spring和SpringBoot监听器

聊到spring boot的生命周期,其实就是事件的监听,这里spring boot的事件监听和spring的有关联,先了解spring的事件监听

spring最开始的监听器父类是这个
在这里插入图片描述
这个是自从spring3.0后可以对你感兴趣的进行监听,而这个实现机制是通过泛型ApplicationListener<E extends ApplicationEvent>来实现的。

As of Spring 3.0, an ApplicationListener can generically declare the event type that it is interested in

后来随着spring boot的出现,又出现了新的监听器接口

public interface SpringApplicationRunListener {
	void starting();

	void environmentPrepared(ConfigurableEnvironment environment);

	void contextPrepared(ConfigurableApplicationContext context);

	void contextLoaded(ConfigurableApplicationContext context);

	void started(ConfigurableApplicationContext context);

	void running(ConfigurableApplicationContext context);
	
	void failed(ConfigurableApplicationContext context, Throwable exception);

}

其实SpringApplicationRunListener并不是新的事物,他最终还是持有的ApplicationListener实现类。典型的新瓶装旧酒


所以下的分析还是围绕ApplicationListener来进行,根据分类可以分为有完整spring bean生命周期的类和没有spring bean生命周期的

一、 非IOClistener

这类就是没有spring生命周期的,这类也是参与感最强的,他贯穿spring boot的整个流程
在new SpringApplication()的时候会调用这句话

setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

需要继续分析getSpringFactoriesInstances

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}

这是其中一种监听器,这种监听器是通过在META-INFO/spring.factories中配置的或者在代码中显示的指定springApplication.addListeners(new MySpringListener());,这类监听器是不走spring的生命周期的,他是通过反射直接创建bean的

这类监听器spring boot会做一个统一的管理,会直接封装到EventPublishingRunListener的变量application中。EventPublishingRunListener,就是SpringApplicationRunListener的实现类,这里也体现出了springboot监听器其实就是持有spring的监听器,依靠spring的监听器来完成的。 这类监听器会参与整个生命周期
在这里插入图片描述

二、 IOC的listener

这类listener最常见是用@Compoment进行注解的。他的初始化是在refreshContext方法中,也就是加载单例bean的时候。这也注定了他只能参加部分监听

下面是一个完整的时间流程

MySpringBeanIOCListener:org.springframework.context.event.ContextRefreshedEvent

MySpringBeanIOCListener:org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent

MySpringBeanIOCListener:org.springframework.boot.context.event.ApplicationStartedEvent

MySpringBeanIOCListener:org.springframework.boot.context.event.ApplicationReadyEvent

从我打印的事件中,可以看出从ContextRefreshedEvent事件开始,才被回调

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值