1. 程式人生 > >關於Spring boot啟動過程判斷當前是否Web環境

關於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