关于Spring boot启动过程判断当前是否Web环境

    SpringBoot 的SpringApplication在初始化过程中执行initialize方法:

@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initialize(Object[] sources) {
		if (sources != null && sources.length > 0) {
			this.sources.addAll(Arrays.asList(sources));
		}
		this.webEnvironment = deduceWebEnvironment();
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		this.mainApplicationClass = deduceMainApplicationClass();
	}

其中这段代码 this.webEnvironment = deduceWebEnvironment(); 的功能是判断当前运行环境是否Web环境,详细代码是:

private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
			"org.springframework.web.context.ConfigurableWebApplicationContext" };

private boolean deduceWebEnvironment() {
		for (String className : WEB_ENVIRONMENT_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return false;
			}
		}
		return true;
}

通过枚举WEB_ENVIRONMENT_CLASSES常量,判断Web环境下主要的类是否能够加载成功(是否当前正在运行的类),有任何一个类无法加载成功都将返回false

你可能感兴趣的:(SpringBoot)