In this tutorial, we'll see how to use a Spring Boot application as a dependency of another project.
2. Spring Boot Packaging
The Spring Boot Maven and Gradle plugins both package our application as executable JARs – such a file can't be used in another project since class files are put into BOOT-INF/classes. This is not a bug, but a feature.
In order to share classes with another project, the best approach to take is to create a separate jar containing shared classes, then make it a dependency of all modules that rely on them.
But if that isn't possible, we can configure the plugin to generate a separate jar that can be used as a dependency.
2.1. Maven Configuration
Let's configure the plugin with a classifier:
... <build> ... <plugins> ... <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <classifier>exec</classifier> </configuration> </plugin> </plugins> </build>
Though, the configuration for Spring Boot 1.x would be a little different:
... <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> <configuration> <classifier>exec</classifier> </configuration> </execution> </executions> </plugin>
This will create two jars, one with the suffix exec as an executable jar, and another as a more typical jar that we can include in other projects.
3. Packaging with Maven Assembly Plugin
We may also use the maven-assembly-plugin to create the dependent jar:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>
If we use this plugin along with the exec classifier in spring-boot-maven-plugin, it will generate three jars. The first two will be the same we saw previously.
The third will have whatever suffix we specified in the <descriptorRef> tag and will contain all the project's transitive dependencies. If we include it in another project, we won't need to separately include Spring dependencies.
In this article, we showed a couple of approaches to packaging a Spring Boot application for use as a dependency in other Maven projects.
As always, the code backing the article is available over on GitHub.