Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude unused parts of dependencies from jar (Maven)

We have a small project with some heavy-weight dependencies (e.g. Spring) of which we only use small parts. Therefore, the JAR we get when packing with all dependencies weighs several megabytes, even for out two-class-server. This seems unnecessary.

Is there a way to restrict JAR assembly to actually used (class) files?

like image 773
Raphael Avatar asked Aug 05 '11 14:08

Raphael


People also ask

How you can exclude dependency in Maven?

You can use Exclude command from the context menu in the Maven dependency diagram to quickly exclude the specified dependency from POM and the respective tool windows. The dependency is also excluded from the Project and Maven tool windows.

How do you exclude a transitive dependency in Maven?

There we can exclude all transitive dependencies without specifying groupId and artifactId of the dependencies. So need to use astric(*) character as groupid and artifactid of the dependency. This wildcard transitive dependencies ignoring is available with maven 3.2.

What is Maven dependency exclusion?

Exclusions are set on a specific dependency in your POM, and are targeted at a specific groupId and artifactId. When you build your project, that artifact will not be added to your project's classpath by way of the dependency in which the exclusion was declared.

Does Maven clean remove dependencies?

It only cleans the project. Show activity on this post. Show activity on this post. With the help of Purging local repository dependencies you need to do that.


2 Answers

You can use the maven-shade-plugin to create a Jar-with-dependencies (your project and the dependencies merged into one big jar) while limiting the classes or packages that are added to that jar. See the includes / excludes page for reference.

If you don't want to manually specify what needs to be included, perhaps there is a way to integrate ProGuard with your build.

like image 172
Sean Patrick Floyd Avatar answered Sep 23 '22 15:09

Sean Patrick Floyd


It's not possible to include only classes which are used. But you can exclude dependencies from your depencies to reduce the JAR size. Only drawback: you need to know what you can exclude and what not.

like image 30
Joachim Rohde Avatar answered Sep 22 '22 15:09

Joachim Rohde