Springboot源码笔记(2)

368 阅读2分钟

这是我参与8月更文挑战的第31天,活动详情查看:8月更文挑战

ApplicationContextInitializer运行流程

初始化过程

(1)初始化ApplicationContextInitializer(流程图)

Springboot-ApplicationContextInitializer.jpg

1.SpringApplication初始化实例

SpringApplication springApplication =new SpringApplication(Application.class);
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进行初始化器实例化
		setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    
		this.mainApplicationClass = deduceMainApplicationClass();
	}

2.setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));对Initializers进行初始化并放入列表中

	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
		return getSpringFactoriesInstances(type, new Class<?>[] {});
	}

getSpringFactoriesInstances使用loadFactoryNames对实现了 ApplicationContextInitializer的类进行了查找,通过createSpringFactoriesInstances对每一个进行实例化,并且使用AnnotationAwareOrderComparator.sort进行排序

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;
	}

SpringFactoriesLoader.loadFactoryNames的具体实现如下

  public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
        String factoryClassName = factoryClass.getName();
        return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
    }

    private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            try {
  Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
 LinkedMultiValueMap result = new LinkedMultiValueMap();
while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
   Entry<?, ?> entry = (Entry)var6.next();
   String factoryClassName = ((String)entry.getKey()).trim();
   String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
   int var10 = var9.length;
   for(int var11 = 0; var11 < var10; ++var11) {
                            String factoryName = var9[var11];
                            result.add(factoryClassName, factoryName.trim());
                        }
                    }
                }
                cache.put(classLoader, result);
                return result;
            } catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
            }
        }
    }

通过读取META-INF/spring.factories中的配置进行注册到result中并进行返回

createSpringFactoriesInstances的具体实现如下

@SuppressWarnings("unchecked")
	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;
	}

主要可以看出是通过BeanUtils.instantiateClass()进行实例化方法并进行返回

**注:**对于第二种初始化器的声明 第二种 ,加入容器是直接在启动类完成的

image-20200731211513100.png 调用后直接加入初始化器的容器当中

image-20200731211936505.png

**注:**对于第二种初始化器的声明 第三种 ,加入容器是直接在启动类完成的

由于使用了在配置文件(resource/application.properties )中设置了初始化类的位置.

从图片可看出在DelegatingApplicationContextInitializer启动的时候便对application.properties中配置的初始化器进行了调用

DelegatingApplicationContextInitializer的initialize方法中首先调用了getInitializeClasses方法

  1. 在properties文件中读取context.initializer.classes所指向的字段

  2. 在循环中调用getInitializeClass对所指向的包名通过ClassUtils转换成Class类型,再使用**Assert.isAssignable(type, instanceClass);**进行类型校验,添加到classes列表当中,并返回

DelegatingApplicationContextInitializer的initialize方法中从getInitializeClasses返回的classes传入applyInitializeClasses

  1. applyInitializeClasses中首先遍历传入的classes调用了instantateInitializer方法:使用BeanUtils对传入的包名,进行实例化对象并返回对应的实例化对象

  2. applyInitializeClasses对从instantateInitializer中返回的对象添加到initializers列表当中

  3. 并将initializers传入到applyInitializers中:对initializers中的实例化对象进行遍历并执行里面的initialize方法

注: 由于DelegatingApplicationContextInitializer的Order为0 所以相比前面的两个初始化器的编写更快的执行

DelegatingApplicationContextInitializer执行过程

ApplicationContextInitializer3 (1).jpg

调用过程

调用过程.png

主要代码
run()
	public ConfigurableApplicationContext run(String... args) {
		StopWatch stopWatch = new StopWatch();
	    stopWatch.start();	//Spring 计时器开启
		ConfigurableApplicationContext context = null;
		Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
		configureHeadlessProperty();
		SpringApplicationRunListeners listeners = getRunListeners(args);
		listeners.starting();//开启监听器
		try {
			ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
			ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
			configureIgnoreBeanInfo(environment);
			Banner printedBanner = printBanner(environment);
			context = createApplicationContext();
			exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
					new Class[] { ConfigurableApplicationContext.class }, context);
			prepareContext(context, environment, listeners, applicationArguments, printedBanner);
			refreshContext(context);
			afterRefresh(context, applicationArguments);
			stopWatch.stop();
			if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
			}
			listeners.started(context);
			callRunners(context, applicationArguments);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, listeners);
			throw new IllegalStateException(ex);
		}

		try {
			listeners.running(context);
		}
		catch (Throwable ex) {
			handleRunFailure(context, ex, exceptionReporters, null);
			throw new IllegalStateException(ex);
		}
		return context;
	}
prepareContext()
	private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
		context.setEnvironment(environment);
		postProcessApplicationContext(context);
		applyInitializers(context);
		listeners.contextPrepared(context);
		if (this.logStartupInfo) {
			logStartupInfo(context.getParent() == null);
			logStartupProfileInfo(context);
		}
		// Add boot specific singleton beans
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
		beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
		if (printedBanner != null) {
			beanFactory.registerSingleton("springBootBanner", printedBanner);
		}
		if (beanFactory instanceof DefaultListableBeanFactory) {
			((DefaultListableBeanFactory) beanFactory)
					.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
		}
		// Load the sources
		Set<Object> sources = getAllSources();
		Assert.notEmpty(sources, "Sources must not be empty");
		load(context, sources.toArray(new Object[0]));
		listeners.contextLoaded(context);
	}
applyInitializers()
	protected void applyInitializers(ConfigurableApplicationContext context) {
		for (ApplicationContextInitializer initializer : getInitializers()) {
			Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
					ApplicationContextInitializer.class);
			Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
			initializer.initialize(context);
		}
	}