SpringBoot版本:2.0.2.RELEASE
SpringFramework版本:5.0.6.RELEASE
SpringFramework事件与监听机制
SpringFramework的事件
随着SpringBoot工程的启动,程序会历经以下代码段:
SpringApplication.run(XXXX.class,args);
....
return new SpringApplication(primarySources).run(args);
....
我们先把目光放在SpringApplication#run方法。该方法有一些命令要重点关注:
....
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
....
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
....
prepareContext(context, environment, listeners, applicationArguments,printedBanner);
refreshContext(context);
....
listeners.started(context);
....
listeners.running(context);
....
在《SpringBoot事件与监听机制》已经说明listeners作为SpringBoot的事件发布者,它的行为就是发布SpringBoot事件。而SpringFramework事件的发布在refreshContext(context)函数里,我们继续进入窥探之。一路跟踪,来到下图位置:
/**
* Refresh the underlying {@link ApplicationContext}.
* @param applicationContext the application context to refresh
*/
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
接下来,程序将离开SpringApplication的内部方法调用,进入AbstractApplicationContext#refresh方法。从类的定义来看,Abs