Skip to content
Advertisement

How to bundle a JAR file with its dependencies using maven

I am developing a Java agent using ByteBuddy, and I need the ByteBuddy library .jar file to be included in the agent .jar file. So far, in order for the agent to run smoothly, I need the ByteBuddy library .jar files to be present in the classpath both at compile time and at runtime. How can I bundle a .jar file such that the agent is self-contained ?

I tried using the shade plugin (as demonstrated here) as well as a few other techniques found on the web, but none of them seem to really include the dependencies in the .jar file, only a reference.

For every technique, I looked in the resulting .jar file (weighs around 5kB every time) and only found the .class files corresponding to the classes I had written, no class files related to ByteBuddy. To be clear, the ByteBuddy library .jar file weighs about 3MB, so I expect my self-contained agent .jar file to weigh around 3MB, as my code is light.

Below is my pom.xml file :

JavaScript

And this is the output I get after running mvn package :

JavaScript

EDIT: So, the reason why all the previous techniques were not working was because of the way I specified the dependencies. This doesn’t get included :

JavaScript

while this does :

JavaScript

I am new to maven so I blindly copy-pasted a piece of code to include the dependencies and I did not spot the error… Thank you very much !

Advertisement

Answer

Sounds like you need to use the “maven-assembly-plugin” with the “jar-with-dependencies” descriptor.

E.g. here is a full example pom file with a dependency on ByteBuddy:

JavaScript

And for the sake of completeness – here is the main class also :

JavaScript

Building this will produce an additional file in the target directory – packaging-example-1.0-SNAPSHOT-jar-with-dependencies.jar

Then you should be able to run it simply with :

JavaScript

to give you the output:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement