在微服务架构中,我们使用的spring cloud是非常依赖springboot的。许多中间间都有对starter的支持,有时这些starter是需要在业务应用启动完成后再进行加载启动的。

例如nacos的client,需要在业务应用启动完成后再进行服务注册。

  1. springboot应用启动完成后会发布ServletWebServerInitializedEvent事件,ServletWebServerInitializedEvent继承了WebServerInitializedEvent
class WebServerStartStopLifecycle implements SmartLifecycle {
   

	private final ServletWebServerApplicationContext applicationContext;

	private final WebServer webServer;

	private volatile boolean running;

	WebServerStartStopLifecycle(ServletWebServerApplicationContext applicationContext, WebServer webServer) {
   
		this.applicationContext = applicationContext;
		this.webServer = webServer;
	}

	@Override
	public void start() {
   
		this.webServer.start();
		this.running = true;
		//发布事件
		this.applicationContext
				.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
	}
}
  1. nacos会监听WebServerInitializedEvent事件,WebServerInitializedEvent继承了ApplicationEvent。
public abstract class AbstractAutoServiceRegistration<R extends Registration>
		implements AutoServiceRegistration, ApplicationContextAware,
		ApplicationListener<WebServerInitializedEvent> {
   
	
	//监听事件
	@Deprecated
	public void bind(WebServerInitializedEvent event) {
   
		ApplicationContext context = event.getApplicationContext();
		if (context instanceof ConfigurableWebServerApplicationContext) {
   
			if ("management".equals(((ConfigurableWebServerApplicationContext) context)
					.getServerNamespace())) {
   
				return;
			}
		}
		this.port.compareAndSet(0, event.getWebServer().getPort());
		this.start();
	}

}

当事件触发后,会触发nacos进行服务注册。