Load external library in java web application

classloader, java, servlets, tomcat

Solution

Since you are using Tomcat, you could leverage the VirtualWebappLoader.

Add a `META-INF/context.xml` whith

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/somepath/myapp">
    <Loader className="org.apache.catalina.loader.VirtualWebappLoader"
              virtualClasspath="/somedir/*.jar"/>
</Context>

Remember also that the virtualClasspath attribute must be a absolute path, as correctly stated in the comment below.

Problem

My scenario is the following: I have a WebApp.war that is deployed to a servlet container. This WebApp.war contains in WEB-INF/lib the following libraries: - lib_a.jar - lib_b.jar I have one other library, say lib_vendor.jar, that I cannot deploy within WebApp/WEB-INF/lib because of licensing issues so I let our customers to copy this library in tomcat/lib after application installation. But since lib_vendor.jar requires lib_a.jar and lib_b.jar that are loaded in the web application class loader, I cannot use lib_vendor.jar. How can I load an external library (not in WEB-INF/lib) in the same classloader of a web application?

Original source