Tomcat的ClassLoader层次结构:
 |
 |
 |
 |
Bootstrap |
System | Common / Catalina Shared / \ Webapp1 Webapp2 ...
|
 |
 |
 |
 |
源代码如下:
org.apache.catalina.startup.Bootstrap类(tomcat主类)
- public final class Bootstrap {
-
-
-
-
- private static int debug = 0;
-
-
-
-
-
-
- public static void main(String args[]) {
-
- for (int i = 0; i < args.length; i++) {
- if ("-debug".equals(args[i]))
- debug = 1;
- }
-
- if (System.getProperty("catalina.base") == null)
- System.setProperty("catalina.base", getCatalinaHome());
-
- ClassLoader commonLoader = null;
- ClassLoader catalinaLoader = null;
- ClassLoader sharedLoader = null;
- try {
- File unpacked[] = new File[1];
- File packed[] = new File[1];
- File packed2[] = new File[2];
- ClassLoaderFactory.setDebug(debug);
- unpacked[0] = new File(getCatalinaHome(),
- "common" + File.separator + "classes");
- packed2[0] = new File(getCatalinaHome(),
- "common" + File.separator + "endorsed");
- packed2[1] = new File(getCatalinaHome(),
- "common" + File.separator + "lib");
- commonLoader =
- ClassLoaderFactory.createClassLoader(unpacked, packed2, null);
- unpacked[0] = new File(getCatalinaHome(),
- "server" + File.separator + "classes");
- packed[0] = new File(getCatalinaHome(),
- "server" + File.separator + "lib");
- catalinaLoader =
- ClassLoaderFactory.createClassLoader(unpacked, packed,
- commonLoader);
- unpacked[0] = new File(getCatalinaBase(),
- "shared" + File.separator + "classes");
- packed[0] = new File(getCatalinaBase(),
- "shared" + File.separator + "lib");
- sharedLoader =
- ClassLoaderFactory.createClassLoader(unpacked, packed,
- commonLoader);
- } catch (Throwable t) {
- log("Class loader creation threw exception", t);
- System.exit(1);
- }
- Thread.currentThread().setContextClassLoader(catalinaLoader);
-
- try {
- SecurityClassLoad.securityClassLoad(catalinaLoader);
-
- if (debug >= 1)
- log("Loading startup class");
- Class startupClass =
- catalinaLoader.loadClass
- ("org.apache.catalina.startup.Catalina");
- Object startupInstance = startupClass.newInstance();
-
- if (debug >= 1)
- log("Setting startup class properties");
- String methodName = "setParentClassLoader";
- Class paramTypes[] = new Class[1];
- paramTypes[0] = Class.forName("java.lang.ClassLoader");
- Object paramValues[] = new Object[1];
- paramValues[0] = sharedLoader;
- Method method =
- startupInstance.getClass().getMethod(methodName, paramTypes);
- method.invoke(startupInstance, paramValues);
-
- if (debug >= 1)
- log("Calling startup class process() method");
- methodName = "process";
- paramTypes = new Class[1];
- paramTypes[0] = args.getClass();
- paramValues = new Object[1];
- paramValues[0] = args;
- method =
- startupInstance.getClass().getMethod(methodName, paramTypes);
- method.invoke(startupInstance, paramValues);
- } catch (Exception e) {
- System.out.println("Exception during startup processing");
- e.printStackTrace(System.out);
- System.exit(2);
- }
- }
其中:
commonLoader = ClassLoaderFactory.createClassLoader(unpacked, packed2, null);
创建common classloader,以AppClassLoader为父ClassLoader
catalinaLoader = ClassLoaderFactory.createClassLoader(unpacked, packed, commonLoader);
创建catalina classloader,以common classloader为父classloader
sharedLoader = ClassLoaderFactory.createClassLoader(unpacked, packed, commonLoader);
创建share classloader,以common classloader为父classloader
Thread.currentThread().setContextClassLoader(catalinaLoader);
设置ContextClassLoader为catalina classloader
org.apache.catalina.startup.ClassLoaderFactory类
- public static ClassLoader createClassLoader(File unpacked[],
- File packed[],
- ClassLoader parent)
- throws Exception {
- if (debug >= 1)
- log("Creating new class loader");
-
- ArrayList list = new ArrayList();
-
- if (unpacked != null) {
- for (int i = 0; i < unpacked.length; i++) {
- File file = unpacked[i];
- if (!file.isDirectory() || !file.exists() || !file.canRead())
- continue;
- if (debug >= 1)
- log(" Including directory " + file.getAbsolutePath());
- URL url = new URL("file", null,
- file.getCanonicalPath() + File.separator);
- list.add(url.toString());
- }
- }
-
- if (packed != null) {
- for (int i = 0; i < packed.length; i++) {
- File directory = packed[i];
- if (!directory.isDirectory() || !directory.exists() ||
- !directory.canRead())
- continue;
- String filenames[] = directory.list();
- for (int j = 0; j < filenames.length; j++) {
- String filename = filenames[j].toLowerCase();
- if (!filename.endsWith(".jar"))
- continue;
- File file = new File(directory, filenames[j]);
- if (debug >= 1)
- log(" Including jar file " + file.getAbsolutePath());
- URL url = new URL("file", null,
- file.getCanonicalPath());
- list.add(url.toString());
- }
- }
- }
-
- String array[] = (String[]) list.toArray(new String[list.size()]);
- StandardClassLoader classLoader = null;
- if (parent == null)
- classLoader = new StandardClassLoader(array);
- else
- classLoader = new StandardClassLoader(array, parent);
- classLoader.setDelegate(true);
- return (classLoader);
- }
ClassLoaderFactory创建的是StandardClassLoader(org.apache.catalina.loader包中)
由Bootstrap类调用Catalina类的process()方法,再调用execute()方法,再调用start()来启动Server实例。
当Tomcat开启每个Context时,是调用的StandardContext的start()方法,其中:
设置Loader为WebappLoader
- if (getLoader() == null) {
- if (getPrivileged()) {
- if (debug >= 1)
- log("Configuring privileged default Loader");
- setLoader(new WebappLoader(this.getClass().getClassLoader()));
- } else {
- if (debug >= 1)
- log("Configuring non-privileged default Loader");
- setLoader(new WebappLoader(getParentClassLoader()));
- }
- }
然后调用:bindThread(),设置当前线程的ClassLoader为WebappLoader的ClassLoader,即为WebappClassLoader
- private ClassLoader bindThread() {
- ClassLoader oldContextClassLoader =
- Thread.currentThread().getContextClassLoader();
- if (getResources() == null)
- return oldContextClassLoader;
- Thread.currentThread().setContextClassLoader
- (getLoader().getClassLoader());
- DirContextURLStreamHandler.bind(getResources());
- if (isUseNaming()) {
- try {
- ContextBindings.bindThread(this, this);
- } catch (NamingException e) {
-
-
- }
- }
- return oldContextClassLoader;
- }
WebappLoader的ClassLoader的赋值如下:
- private String loaderClass =
- "org.apache.catalina.loader.WebappClassLoader";
- ......
- public void start() throws LifecycleException {
-
- if (started)
- throw new LifecycleException
- (sm.getString("webappLoader.alreadyStarted"));
- if (debug >= 1)
- log(sm.getString("webappLoader.starting"));
- lifecycle.fireLifecycleEvent(START_EVENT, null);
- started = true;
- if (container.getResources() == null)
- return;
-
- URLStreamHandlerFactory streamHandlerFactory =
- new DirContextURLStreamHandlerFactory();
- try {
- URL.setURLStreamHandlerFactory(streamHandlerFactory);
- } catch (Throwable t) {
-
- }
-
- try {
- classLoader = createClassLoader();
- classLoader.setResources(container.getResources());
- classLoader.setDebug(this.debug);
- classLoader.setDelegate(this.delegate);
- if (container instanceof StandardContext)
- classLoader.setAntiJARLocking(((StandardContext) container).getAntiJARLocking());
- for (int i = 0; i < repositories.length; i++) {
- classLoader.addRepository(repositories[i]);
- }
-
- setRepositories();
- setClassPath();
- setPermissions();
- if (classLoader instanceof Lifecycle)
- ((Lifecycle) classLoader).start();
-
- DirContextURLStreamHandler.bind
- ((ClassLoader) classLoader, this.container.getResources());
- } catch (Throwable t) {
- throw new LifecycleException("start: ", t);
- }
-
- validatePackages();
-
- if (reloadable) {
- log(sm.getString("webappLoader.reloading"));
- try {
- threadStart();
- } catch (IllegalStateException e) {
- throw new LifecycleException(e);
- }
- }
- }
- ......
- private WebappClassLoader createClassLoader()
- throws Exception {
- Class clazz = Class.forName(loaderClass);
- WebappClassLoader classLoader = null;
- if (parentClassLoader == null) {
-
-
- classLoader = (WebappClassLoader) clazz.newInstance();
- } else {
- Class[] argTypes = { ClassLoader.class };
- Object[] args = { parentClassLoader };
- Constructor constr = clazz.getConstructor(argTypes);
- classLoader = (WebappClassLoader) constr.newInstance(args);
- }
- return classLoader;
- }
在WebappClassLoader中,其findClass的搜索顺序与一般的ClassLoader的搜索顺序不同。
一般的ClassLoader的搜索顺序为:
将其委托给父ClassLoader,如果父ClassLoader不能载入相应类,则才交给自己处理
但是WebappClassLoader中,其是先由自己来处理,如果不行再委托给父ClassLoader
相关源代码如下:
- Class clazz = null;
- try {
- if (debug >= 4)
- log(" findClassInternal(" + name + ")");
- try {
- clazz = findClassInternal(name);
- } catch(ClassNotFoundException cnfe) {
- if (!hasExternalRepositories) {
- throw cnfe;
- }
- } catch(AccessControlException ace) {
- ace.printStackTrace();
- throw new ClassNotFoundException(name);
- } catch (RuntimeException e) {
- if (debug >= 4)
- log(" -->RuntimeException Rethrown", e);
- throw e;
- }
- if ((clazz == null) && hasExternalRepositories) {
- try {
- clazz = super.findClass(name);
- } catch(AccessControlException ace) {
- throw new ClassNotFoundException(name);
- } catch (RuntimeException e) {
- if (debug >= 4)
- log(" -->RuntimeException Rethrown", e);
- throw e;
- }
- }
- if (clazz == null) {
- if (debug >= 3)
- log(" --> Returning ClassNotFoundException");
- throw new ClassNotFoundException(name);
- }
- } catch (ClassNotFoundException e) {
- if (debug >= 3)
- log(" --> Passing on ClassNotFoundException", e);
- throw e;
- }
以下引自tomcat的说明文档,说明了加载类的顺序
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
- /WEB-INF/classes of your web application
- /WEB-INF/lib/*.jar of your web application
- Bootstrap classes of your JVM
- System class loader classses (described above)
- $CATALINA_HOME/common/classes
- $CATALINA_HOME/common/endorsed/*.jar
- $CATALINA_HOME/common/lib/*.jar
- $CATALINA_BASE/shared/classes
- $CATALINA_BASE/shared/lib/*.jar
Class Loader HOW-TO
Overview |
Like many server applications, Tomcat 6 installs a variety of class loaders (that is, classes that implement java.lang.ClassLoader ) to allow different portions of the container, and the web applications running on the container, to have access to different repositories of available classes and resources. This mechanism is used to provide the functionality defined in the Servlet Specification, version 2.4 -- in particular, Sections 9.4 and 9.6.
In a J2SE 2 (that is, J2SE 1.2 or later) environment, class loaders are arranged in a parent-child tree. Normally, when a class loader is asked to load a particular class or resource, it delegates the request to a parent class loader first, and then looks in its own repositories only if the parent class loader(s) cannot find the requested class or resource. The model for web application class loaders differs slightly from this, as discussed below, but the main principles are the same.
When Tomcat 6 is started, it creates a set of class loaders that are organized into the following parent-child relationships, where the parent class loader is above the child class loader:
 |
 |
 |
 |
Bootstrap
|
System
|
Common
/ Webapp1 Webapp2 ...
|
 |
 |
 |
 |
The characteristics of each of these class loaders, including the source of classes and resources that they make visible, are discussed in detail in the following section.
|
Class Loader Definitions |
As indicated in the diagram above, Tomcat 6 creates the following class loaders as it is initialized:
- Bootstrap - This class loader contains the basic runtime classes provided by the Java Virtual Machine, plus any classes from JAR files present in the System Extensions directory (
$JAVA_HOME/jre/lib/ext ). NOTE - Some JVMs may implement this as more than one class loader, or it may not be visible (as a class loader) at all.
- System - This class loader is normally initialized from the contents of the
CLASSPATH environment variable. All such classes are visible to both Tomcat internal classes, and to web applications. However, the standard Tomcat 6 startup scripts ($CATALINA_HOME/bin/catalina.sh or%CATALINA_HOME%\bin\catalina.bat ) totally ignore the contents of the CLASSPATH environment variable itself, and instead build the System class loader from the following repositories:
- $CATALINA_HOME/bin/bootstrap.jar - Contains the main() method that is used to initialize the Tomcat 6 server, and the class loader implementation classes it depends on.
- $CATALINA_HOME/bin/tomcat-juli.jar - Package renamed Commons logging API, and java.util.logging LogManager.
- Common - This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. Normally, application classes should NOT be placed here. All unpacked classes and resources in
$CATALINA_HOME/lib , as well as classes and resources in JAR files are made visible through this class loader. By default, that includes the following:
- annotations-api.jar - JEE annotations classes.
- catalina.jar - Implementation of the Catalina servlet container portion of Tomcat 6.
- catalina-ant.jar - Tomcat Catalina Ant tasks.
- catalina-ha.jar - High availability package.
- catalina-tribes.jar - Group communication package.
- el-api.jar - EL 2.1 API.
- jasper.jar - Jasper 2 Compiler and Runtime.
- jasper-el.jar - Jasper 2 EL implementation.
- jasper-jdt.jar - Eclipse JDT 3.2 Java compiler.
- jsp-api.jar - JSP 2.1 API.
- servlet-api.jar - Servlet 2.5 API.
- tomcat-coyote.jar - Tomcat connectors and utility classes.
- tomcat-dbcp.jar - package renamed database connection pool based on Commons DBCP.
- tomcat-i18n-**.jar - Optional JARs containing resource bundles for other languages. As default bundles are also included in each individual JAR, they can be safely removed if no internationalization of messages is needed.
- WebappX - A class loader is created for each web application that is deployed in a single Tomcat 6 instance. All unpacked classes and resources in the
/WEB-INF/classes directory of your web application archive, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application archive, are made visible to the containing web application, but to no others.
As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.3, section 9.7.2 Web Application Classloader). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. There are exceptions. Classes which are part of the JRE base classes cannot be overriden. For some classes (such as the XML parser components in J2SE 1.4+), the J2SE 1.4 endorsed feature can be used. Last, any JAR containing servlet API classes will be ignored by the classloader. All other class loaders in Tomcat 6 follow the usual delegation pattern.
Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
- Bootstrap classes of your JVM
- System class loader classes (described above)
- /WEB-INF/classes of your web application
- /WEB-INF/lib/*.jar of your web application
- $CATALINA_HOME/lib
- $CATALINA_HOME/lib/*.jar
|
|