Overriding a class file from a JAR library in a Java web application

In my Java web application, I have the following files:

/WEB-INF/classes/com/example/Foo.class /WEB-INF/lib/example.jar <-- contains the class "com.example.Foo" 

Will the class defined in the classes directory be used instead of the class defined in example.jar ?

Thanks.

+8
java classpath java-ee jar
source share
2 answers

The answer depends on your container, it depends on the container. In general, / WEB -INF / classes is preferable to classes in the jar file in WEB-INF / lib.

For Tomcat, the order is as follows:

Therefore, from the point of view of a web application, loading classes or resources looks in the following repositories in the following order:

  • The initial classes of your JVM
  • System Class Loader Classes
  • / WEB-INF / classes of your web application
  • / WEB-INF / lib / *. jar of your web application.
  • Common Class Loader Classes

But if you use a different container, you need to refer to the documentation for this server.

+13
source share

So there is only one way to find out. I wrote a test :)

 ├── example │  ├── example.iml │  ├── pom.xml │  └── src │  ├── main │  │  └── java │  │  └── test │  │  ├── Bar.java │  │  └── Foo.java │  └── test │  └── java │  └── testexample │  └── TestFoo.java ├── pom.xml ├── test.iml └── web ├── pom.xml ├── src │  ├── main │  │  └── java │  │  └── test │  │  └── Foo.java │  └── test │  └── java │  └── junittest │  └── TestFooInWeb.java └── web.iml 16 directories, 11 files 

I found that in TestFoo.java prints

 Hello from example.jar Hello from example.jar 

And for TestFooInWeb.java prints

 Hello from web app Hello from web app 

Both tests have this in a test class:

 public class TestFooInWeb/TestFoo { @Test public void testHello() { System.out.println(new Foo().sayHello()); } @Test public void testHelloFromBar() { new Bar().sayHelloForFoo(); } } 

So, everything is at the end, I stand fixed. You can load a completely different class, and all Jar files will use this new class. This makes sense because ClassLoader first look at the class directory. I am not sure if I agree with this because it sounds suspicious and I can overwrite security classes.

+7
source share

All Articles