Reduce jar size in Maven Project

5

I am generating a jar from a Maven project and the size is absurdly high.

What steps can I take to reduce the size of this jar?

    
asked by anonymous 18.05.2016 / 14:23

3 answers

1

An alternative is to create the jar without the dependencies. The jar will contain only the project classes and will be greatly reduced. In that case, you will need to put the jars that the project needs somewhere and add those jars in the project's classpath.

Your pom.xml looks something like this:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
                <mainClass>testes.testes.App</mainClass>
            </manifest>
            <manifestEntries>
                <Class-Path>poi-ooxml-3.14.jar poi-3.14.jar</Class-Path>
            </manifestEntries>
          </archive>
        </configuration>
    </plugin>

In this way, the jar will be created without the dependencies. the <Class-Path> snippet will be added to the MANIFEST.MF file.

    
01.09.2016 / 18:03
3

Make sure any dependencies added to your POM.XML can be removed.

In addition, often a dependency depends on several other libs. If you are sure that any of them is not in use you can remove it using

Ex:

<dependency>
  <groupId>br.com.teste</groupId>
    <artifactId>artefato-teste</artifactId>
    <version>2.0</version>
    <exclusions>
      <exclusion>
        <groupId>br.com.teste</groupId>
        <artifactId>sub-artefato-teste</artifactId>
      </exclusion>
    </exclusions>
</dependency>
    
18.05.2016 / 16:05
3

In addition to following peer advice and reviewing dependencies and transitive dependencies, there are tools that can help you.

A first way to reduce Jar size is to compress using Pac200 . You can do this with Maven using the Maven Pack200 Plugin plugin.

Another way is to use a plugin like Apache Maven Shade Plugin that can create a Uber Jar (ie, that only packs classes actually used by the application) or something like ProGuard which, in addition to removing unused classes, also decreases, "obfuscates" and optimizes the code.

All these tools have their limitations. For example, some of the application servers do not work with jars packed with pac200. Minimizers and optimizers can also be dangerous, they can not detect reflection-loaded classes, and often require a certain manual configuration effort (exclude classes from the minification process) when used with more complex frameworks and libraries. It is also not uncommon to have problems using an obfuscator with new versions of Java (it usually takes a while for ProGuard to be updated).

    
18.05.2016 / 18:08