springboot SpringApplication类初始化过程学习

一 背景:

  springboot 是目前项目采用的框架,之前没有使用过,快速看下入口:这是一个标准的Java应用程序的入口方法,可以直接启动。

@SpringBootApplication
public class XXApplication {

	public static void main(String[] args) {
		SpringApplication.run(SearchCoreApplication.class, args);
	}

}

二 核心注解:

 @SpringBootApplication ,核心注解,用以标注对应的入口类是应用的启动类。

它是一组注解的组合:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};

	/**
	 * Exclude specific auto-configuration class names such that they will never be
	 * applied.
	 * @return the class names to exclude
	 * @since 1.3.0
	 */
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};

	/**
	 * Base packages to scan for annotated components. Use {@link #scanBasePackageClasses}
	 * for a type-safe alternative to String-based package names.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};

	/**
	 * Type-safe alternative to {@link #scanBasePackages} for specifying the packages to
	 * scan for annotated components. The package of each class specified will be scanned.
	 * <p>
	 * Consider creating a special no-op marker class or interface in each package that
	 * serves no purpose other than being referenced by this attribute.
	 * @return base packages to scan
	 * @since 1.3.0
	 */
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

有:配置相关的SpringBootConfiguration,还有EnableAutoConfiguration:启动自动配置,会让springboot  根据项目依赖的jar自动配置相关的配置项(还需要maven)。ComponentScan 扫描配置。默认会扫描@SpringBootConfiguration 所在的类的同级包及子包。

  三  初始化

    springboot再进行SpringApplication 对象实例化时会加载META-INF/spring.factories文件,讲该配置文件中的配置载入到Spring容器,进行自动配置。这里只是从SpringApplication.run()去看SpringApplication实例化的过程,不关注run()的完整启动流程。

SpringApplication
	public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
		return run(new Class<?>[] { primarySource }, args);
	}
	public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
		return new SpringApplication(primarySources).run(args);
	}

run方法里面是在创建SpringApplication 对象实例,下面来看创建SpringApplication对象实例的代码:

	public SpringApplication(Class<?>... primarySources) {
		this(null, primarySources);
	}
    	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();
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		this.mainApplicationClass = deduceMainApplicationClass();
	}

可以看到做了如下几件事:

  1. 如果sources⻓度⼤于0的话,加⼊到SpringApplication的sources中,该sources是⼀个LinkedHashSet.(去重)

  2. 调⽤deduceWebEnvironment⽅法判断是否是web环境(默认servlet)

  3. 设置initializers.

  4. 设置Listeners.

  5. 设置mainApplicationClass.

3.1 deduceFromClasspath

	static WebApplicationType deduceFromClasspath() {
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		return WebApplicationType.SERVLET;
	}

NONE: 应用程序不是web应用,也不应该用web服务器去启动,其余的SERVLET、REACTIVE都是web应用.区别我初步认为REACTIVE反应式是 异步非阻塞的。(后面再看吧)

具体的判断逻辑如下:

  • WebApplicationType.REACTIVE  classpath下存在org.springframework.web.reactive.DispatcherHandler

  • WebApplicationType.SERVLET classpath下存在javax.servlet.Servlet或者org.springframework.web.context.ConfigurableWebApplicationContext

  • WebApplicationType.NONE 不满足以上条件。

3.2  getSpringFactoriesInstances

   再设置初始化setInitializers调用了getSpringFactoriesInstances

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

该⽅法逻辑如下:

  1. ⾸先获得ClassLoader.
  2. 调⽤SpringFactoriesLoader#loadFactoryNames进⾏加载,然后放⼊到LinkedHashSet进⾏去重.
  3. 调⽤createSpringFactoriesInstances进⾏初始化
  4. 排序

3.2.1 loadfactorynames

其中SpringFactoriesLoader.loadFactoryNames 方法很重要,这个方法是spring-core中提供的从META-INF/spring.factories中获取指定的类(key)的同一入口方法。代码如下:

  

SpringFactoriesLoader.java
	
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
		String factoryClassName = factoryClass.getName();
		return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
	}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
		MultiValueMap<String, String> result = cache.get(classLoader);
		if (result != null) {
			return result;
		}

		try {
			Enumeration<URL> urls = (classLoader != null ?
					classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
			result = new LinkedMultiValueMap<>();
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				UrlResource resource = new UrlResource(url);
				Properties properties = PropertiesLoaderUtils.loadProperties(resource);
				for (Map.Entry<?, ?> entry : properties.entrySet()) {
					String factoryClassName = ((String) entry.getKey()).trim();
					for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
						result.add(factoryClassName, factoryName.trim());
					}
				}
			}
			cache.put(classLoader, result);
			return result;
		}
		catch (IOException ex) {
			throw new IllegalArgumentException("Unable to load factories from location [" +
					FACTORIES_RESOURCE_LOCATION + "]", ex);
		}
	}

可以看到加载了一个常量:

public final class SpringFactoriesLoader {

   /**
    * The location to look for factories.
    * <p>Can be present in multiple JAR files.
    */
   public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

就是META-INF/spring.factories。再看load代码的逻辑

  • 获得factoryClassName,对于当前来说factoryClassName =org.springframework.context.ApplicationContextInitializer.
  • 通过传⼊的classLoader加载META-INF/spring.factories⽂件.
  • 通过调⽤PropertiesLoaderUtils#loadProperties将其转为Properties.
  • 获得factoryClassName对应的值进⾏返回.
    对于当前来说,由于我们只加⼊了spring-boot-starter-web的依赖,因此会加载如下的配置:
  • 在spring-boot/META-INF/spring.factories(这个文件很重要,用来指导spring boot找到指定的自动配置文件)类型有很多,有
    PropertySourceLoader 支持配置文件的格式,ApplicationListener=监听器类。还有下面要看的初始化类ApplicationContextInitializer

# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

在spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories
中.org.springframework.context.ApplicationContextInitializer值如下:

# Initializers org.springframework.context.ApplicationContextInitializer=\ org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\ org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

因此会加载6个初始化类.

3.2.2  createSpringFactoriesInstances

private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
			ClassLoader classLoader, Object[] args, Set<String> names) {
		List<T> instances = new ArrayList<>(names.size());
		for (String name : names) {
			try {
				Class<?> instanceClass = ClassUtils.forName(name, classLoader);
				Assert.isAssignable(type, instanceClass);
				Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
				T instance = (T) BeanUtils.instantiateClass(constructor, args);
				instances.add(instance);
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
			}
		}
		return instances;
	}

主要逻辑:遍历传⼊的names(之前通过SpringFactoriesLoader加载的类名).通过遍历,依次调⽤其构造器进⾏初始化.加⼊到
instances.然后进⾏返回.

3.3 设置监听器setListeners

跟上面的3.2 一个流程,调⽤getSpringFactoriesInstances加载META-INF/spring.factories中配置

# Application Listeners
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.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

listener是spring的事件监听器,是一种观察者模式.再看吧。

3.4 获得应⽤的启动类


	private Class<?> deduceMainApplicationClass() {
		try {
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		}
		catch (ClassNotFoundException ex) {
			// Swallow and continue
		}
		return null;
	}

先梳理到这里。通过 SpringApplication 类的实例化过程,可以指导做一些准备工作或者自定义监听器。

通过使用了注解的自动配置,从META-INF/spring.factories⽂件将其中的对应配置汇总加载到spring框架的容器。进行自动配置。

发布了521 篇原创文章 · 获赞 94 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/bohu83/article/details/103001719
今日推荐