SpringApplication 初始化
基于 springboot3.2 和 springframework6.1.4
初始化代码解释
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
这是来自Spring Boot框架的SpringApplication
类的代码片段。该构造函数用于创建SpringApplication
的新实例,这是一个关键的类,负责引导和启动Spring应用程序。
让我们分解一下这个构造函数的关键方面:
-
资源加载器(Resource Loader):
resourceLoader
参数表示要由应用程序上下文使用的资源加载器。它有助于从不同来源加载资源。 -
主要来源(Primary Sources):
primarySources
参数表示主要的bean来源。这些类被视为配置Spring应用程序上下文的主要来源。 -
Web应用程序类型(Web Application Type):
webApplicationType
是从类路径中推断出来的。它表示Web应用程序的类型(例如,Servlet、Reactive、None)。 -
引导注册表初始化器(Bootstrap Registry Initializers):
bootstrapRegistryInitializers
是BootstrapRegistryInitializer
实例的列表。它们负责在应用程序引导阶段自定义BootstrapRegistry
。 -
初始化器和监听器(Initializers and Listeners):构造函数通过使用
getSpringFactoriesInstances
从Spring工厂获取实例来设置初始化器和监听器。
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.env.EnvironmentPostProcessorApplicationListener
- 主应用程序类(Main Application Class):
mainApplicationClass
是通过推断得出的,表示应用程序的主类。