Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external library in java web application

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?

like image 370
Joao Pereira Avatar asked Dec 04 '12 14:12

Joao Pereira


People also ask

How do you use libraries in Java?

To use a library, you have to add it to your classpath, which you pass into the javac and java commands using the -cp argument. As long as you do that, you can use classes from a library exactly like you can use a regular Java class or a class that you create- they're all just Java classes.

What are external libraries?

What are External Libraries? External Libraries are pieces of pre-written code that is easy to implement. You don't really have to know exactly anything about what is inside that code, you just need to know how to use it.


1 Answers

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.

like image 109
Carlo Pellegrini Avatar answered Oct 06 '22 09:10

Carlo Pellegrini