功能位置 |
---|
// **************** org.springframework.boot.SpringApplication ******************/
private boolean webEnvironment;
private void initialize(Object[] sources) {
//略...
this.webEnvironment = deduceWebEnvironment();
//略...
}
推断当前环境是否是web环境,并把推断结果(boolean)保存到SpringApplication 实例中。
如何推断的呢?其实就是加载 web环境下才有的类,加载成功说明是web环境,否则不是web环境。
下面是源码:
源码:initialize(...)
|- deduceWebEnvironment()
// **************** org.springframework.boot.SpringApplication ******************/
private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
"org.springframework.web.context.ConfigurableWebApplicationContext" };
/**
* 检查classpath中是否同时存在{ "javax.servlet.Servlet","ConfigurableWebApplicationContext" },
* 如果存在的话,返回true.否则返回false.
*/
private boolean deduceWebEnvironment() {
for (String className : WEB_ENVIRONMENT_CLASSES) {
// classpath 下面没有指定的两个类,则表示不是web环境
if (!ClassUtils.isPresent(className, null)) {
return false;
}
}
return true;
}
// **************** org.springframework.util.ClassUtils ******************/
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
// 当前类加载器加载 className 指定的类,报异常则表示classpath下没有该类
forName(className, classLoader);
return true;
}
catch (Throwable ex) {
// Class or one of its dependencies is not present...
return false;
}
}
1.1-Q1 设置这个webEnvironment 做什么用?
搜索(ctrl+shift+g)所有读取 webEnvironment
的地方,打上断点,debug 程序看看…