聊到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
事件开始,才被回调