SpringBoot2 源码学习笔记(三)

创建哪种web应用类型是怎么决定的

首先看看返回web应用类型的方法,我们可以看到这个类并没有传入任何变量,包括执行的时候也没有依赖外部的变量,那么它是怎么决定采用哪种应用类型的呢?

    private WebApplicationType deduceWebApplicationType() {
		if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
				&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		for (String className : WEB_ENVIRONMENT_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		return WebApplicationType.SERVLET;
	}

我们进入 ClassUtils.isPresent 方法。我们可以看到这个方法的主要作用是通过反射判断相应的类存不存在。

所以,我猜测 SpringBoot 通过我们引入的 jar 来帮助我们自动配置相应的 web 应用类型,当然,如果我们同时引入了多个相关的jar包,那么则根据优先级来设定究竟需要哪一个。

    /**
	 * Determine whether the {@link Class} identified by the supplied name is present
	 * and can be loaded. Will return {@code false} if either the class or
	 * one of its dependencies is not present or cannot be loaded.
	 * @param className the name of the class to check
	 * @param classLoader the class loader to use
	 * (may be {@code null} which indicates the default class loader)
	 * @return whether the specified class is present
	 */
	public static boolean isPresent(String className, @Nullable ClassLoader classLoader) {
		try {
			forName(className, classLoader);
			return true;
		}
		catch (Throwable ex) {
			// Class or one of its dependencies is not present...
			return false;
		}
	}

猜你喜欢

转载自blog.csdn.net/buyulian/article/details/82314181