How to adding classes to the JAR File's Classpath in a Maven sprint boot app?

How to adding classes to the JAR File's Classpath in a Maven sprint boot app?
Photo by Tonya Wright / Unsplash

When using Maven, if we want to rely on a local jar package, we usually use <scope>system</scope> and  <systemPath>{yourlibpath}</systemPath> to handle it.

By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run your application.

But if you just do the above, when you use the SpringBoot packaging plugin to generate a jar package, you will find that the jar package will not be typed in, and an error will occur. The error usually is a runtime error like "NoClassDefFoundError".

Best Practice: use spring-boot-maven-plugin includeSystemScope true

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <includeSystemScope>true</includeSystemScope>
    </configuration>
</plugin>

Optional Solution: use maven-jar-plugin manifestEntries

if your jar file will not executed by Spring Boot, you want run it via java command.
You can list system lib jar files in <manifestEntries /> section via maven-jar-plugin.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>com.SprintBootApplication</mainClass>
            </manifest>
            <manifestEntries>
                <Class-Path>your external jar files</Class-Path>
            </manifestEntries>
        </archive>
    </configuration>
</plugin>

What is MANIFEST.MF?

by doing the above, you will see a MANIFEST.MF is packaged inside your app's jar.

A tip to check jar file in your IDE

click any jar file in your IDE, add it as Library dependency for your app. Then you can view what are packaged inside the jar.

Then in the Project explorer, you can view the external dependencies.

References

Apache Maven Archiver – Set Up The Classpath
Adding Classes to the JAR File’s Classpath (The Java™ Tutorials > Deployment > Packaging Programs in JAR Files)
This deployment Java tutorial describes development and deployment of applets, Java Web Start applications, rich Internet applications, and JAR related tools
Working with Manifest Files: The Basics (The Java™ Tutorials > Deployment > Packaging Programs in JAR Files)
This deployment Java tutorial describes development and deployment of applets, Java Web Start applications, rich Internet applications, and JAR related tools

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe