springboot中判断当前项目是否为web项目
https://blog.csdn.net/txba6868/article/details/80732475
springboot在启动的时候需要检测当前项目是否是一个web项目,检测方式为判断classpath中是否有以下final变量中定义的两个参数:
private static final String[] WEB_ENVIRONMENT_CLASSES = new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};
源码:
代码来源:org.springframework.boot.SpringApplication.initialize(Oeject[] sources) this.webEnvironment = this.deduceWebEnvironment(); //检测当前项目是否为web项目
代码来源:org.springframework.boot.SpringApplication.deduceWebEnvironment() private boolean deduceWebEnvironment() { String[] var1 = WEB_ENVIRONMENT_CLASSES; int var2 = var1.length; //从全局变量中取出标识web项目的参数,遍历 for(int var3 = 0; var3 < var2; ++var3) { String className = var1[var3]; if (!ClassUtils.isPresent(className, (ClassLoader)null)) { return false; } } return true; }
代码来源:org.springframework.util.ClassUtils.isPresent(String className,ClassLoader classLoc) public static boolean isPresent(String className, ClassLoader classLoader) { try { forName(className, classLoader); return true; } catch (Throwable var3) { return false; } }
代码来源:org.springframework.util.ClassUtils.forName(String name,ClassLoader classLoader) public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Assert.notNull(name, "Name must not be null"); //首先检查内存中当前的className是否存在 Class<?> clazz = resolvePrimitiveClassName(name); if (clazz == null) { clazz = (Class)commonClassCache.get(name); } if (clazz != null) { return clazz; } else { Class elementClass; String elementName; if (name.endsWith("[]")) { elementName = name.substring(0, name.length() - "[]".length()); elementClass = forName(elementName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } else if (name.startsWith("[L") && name.endsWith(";")) { elementName = name.substring("[L".length(), name.length() - 1); elementClass = forName(elementName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } else if (name.startsWith("[")) { elementName = name.substring("[".length()); elementClass = forName(elementName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } else { //内存中不存在时将调用系统的classLoader从系统指定路径进行加载 ClassLoader clToUse = classLoader; if (classLoader == null) { clToUse = getDefaultClassLoader(); } //加载执行 try { return clToUse != null ? clToUse.loadClass(name) : Class.forName(name); } catch (ClassNotFoundException var9) { int lastDotIndex = name.lastIndexOf(46); if (lastDotIndex != -1) { String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1); try { return clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName); } catch (ClassNotFoundException var8) { ; } } throw var9; } } } }
上述代码提到了类加载(classLoader)。具体的类加载机制请看这里。
关于类加载的介绍,转自: https://blog.csdn.net/briblue/article/details/54973413。