How to use an external JAR in a Spring Boot application

This article presents different ways to include an external JAR when starting a Spring Boot application from the Command Line.

It is fairly common that you need to patch a Spring Boot application with an external JAR file and you are not able to repackage the full application. In some other cases, you are not able to change the pom.xml file as well.

To solve this issue, you can rely on a feature of the PropertiesLauncher. This is a launcher for archives with user-configured classpath and main class via a properties file. It will look in various places for a properties file to extract loader settings.

We can instruct the PropertiesLauncher to search for additional JAR files in other folders as well.

More in detail, we can rely on the property loader.path . This property includes directories (which are scanned recursively for jar and zip files), archive paths, a directory within an archive that is scanned for jar files (for example, dependencies.jar!/lib), or wildcard patterns (for the default JVM behavior). Archive paths can be relative to loader.home or anywhere in the file system with a jar:file: prefix.

How to configure the loader.path

There are two simple ways to do that: the simplest one is to add the property on the command line. Also, you will not launch the Spring Boot application in the usual format (java -jar application). On the other hand, you will launch the PropertiesLauncher class but adding in the classpath your Spring Boot application.

Example:

  • Your Spring Boot application is: myapp-1.0-SNAPSHOT.jar
  • Your external jars are in the folder /home/user/extlib

Here is how to launch your Spring Boot application

java -cp target/myapp-1.0-SNAPSHOT.jar -Dloader.path=/home/user/extlib org.springframework.boot.loader.PropertiesLauncher

If you prefer, you can keep the standard way to launch a Spring Boot application:

java -Dloader.path=/home/user/extlib-jar target/myapp-1.0-SNAPSHOT.jar

You should however instruct the Spring Boot Maven plugin to use the PropertiesLauncher by including the following configuration:

<build> 
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>  
                <layout>ZIP</layout>  
            </configuration>
        </plugin>
    </plugins>
</build>
Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon