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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章