简体   繁体   中英

How to deal with fat jar dependency

I have a proprietary dependency that I use in my project that I can not refuse. It was built in one big fat jar with all dependent packages collected inside. By all I mean even common ones like slf4j-api, apache-commons, javax packages, etc.

Using it together with my own list of declared dependecies is risky because there's always a race in classloader on which class will be loaded first - mine or outdated class inside fat jar.

I was wondering is there a way around this problem? How to treat such fat jars? I'm using maven for dependency management.

In Maven, the order in which you define dependencies in your POM is significant. If you list them in the correct order, they should be added to the jar in that order, and whichever class is higher in the file, that's the one that will get loaded first.

If you will compose your runtime classpath out of multiple jars, then again, it's a matter of putting the jars in the right order.

I think that there's another way. I can wrap this library jar in its own custom classloader

URLClassLoader c1 = new URLClassLoader(new Url[] { new URL("file:lib/fatJarDep.jar"});

and create a factory that will instantiate classes of this library using this isolated classloader

Class.forName("className", true, c1);

If the jar has all dependency class extracted inside you can't exclude them from classloading, so same dependecy in your project may conflict.

You should edit the fat jar and manually remove the classes to make a light version, then install it in your repo and refer to it in your pom.

If you know that some functionalities of the fat jar will work when you exclude some fo their dependencies or you want to include them yourself, you can try this:

  1. Make a maven project that depends on the fat jar only
  2. Use maven-shade-plugin , in particular it's relocation feature to exclude packages you don't want, or to just relocate all the jar's classes into another package, and thus move them out of the way.
  3. Use the project's artifact instead of fat propietary jar in your other project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM