title: Force a custom ClassLoader for WAR files?
body: <p>Is there a standard way (i.e. defined by some Java/J2EE/etc. spec) to provide a custom class loader to a Java Servlet Container which should be used to load a WAR file?</p>
  
  <p>On a new project we are extending a large commercial Java software package (Foo) with web services which requires some flexibility of deployment (as separate services, etc).  In particular, we want to avoid the necessity to include in each WAR file all of the Foo software dependency Jar files as they are numerous, large, and will be changing with patch/bugfix releases as we develop.  Similarly, it is highly undesirable to have to copy all of the dependencies into each Servlet container's "lib" directory.</p>
  
  <p>Ideally, I would like to tell the Java application server that these WAR files must be loaded using a custom class loader which I will provide which automatically includes the Foo software dependency Jars.  Something like this (in Java-pseudocode):</p>
  
  <pre class="lang-java prettyprint-override"><code>public class MyWarFileClassLoader extends ClassLoader {
    protected URLClassLoader urlcl;
    public MyWarFileClassLoader(File warFile) {
      File installDir = System.getEnv("FOO_HOME");
      List&lt;File&gt; fooEntries = new File(installDir, "jars").listFiles("*.jar");
      fooEntries.add(new File(installDir, "resources"));
      fooEntries.add(warFile);
      this.urlcl = new URLClassLoader(fooEntries);
    }
    public Class&lt;?&gt; findClass(String name) {
      return this.urlcl.findClass(name);
    }
  }
  </code></pre>
  
  <p>If there is no <em>standard</em> way to do this, is there a straightforward way to achieve the same goal for several WAR files, regardless of the target Servlet Container?</p>
  
  <p><strong>[Edit]</strong></p>
  
  <p>To put it another way: is there a common pattern for allowing WAR files to manage their own dependencies at runtime instead of relying on the Servlet Container configuration?  I could, of course, have the WAR file manifest include a <code>Class-Path</code> attribute but then the entries are still "hardcoded" at build time rather than detected automatically at runtime.</p>