Building Reusable Spring Boot Libraries with Gradle

Building Reusable Spring Boot Libraries with Gradle

Architectural Guide: Building Reusable Spring Boot Libraries with Gradle

In this tutorial, we are going to learn how to package the Spring Boot project as a reusable library.
By default, Spring Boot is configured to package everything into a fat JAR file that contains all the dependencies and loader classes.
To create our project as a library, we need to disable the fat JAR creation by creating a normal JAR file that only contains the project’s own classes and property files.
If you are creating the multi-project build parent application, please consider following our tutorial.

Create a Spring Boot project

You can use a Spring initializer for creating a Spring Boot project. Here is my sample project.
Article Image
The structure of the library project is similar to an application project; we don't have the main class. So, delete the main class. We also need to delete the main test class.
If you are using a multi-project setup, please include the project inside settings.gradle
bash
include 'csbyte-service'

Setting build.gradle

Now, try to build your project with Gradle
bash
 ./gradlew build
You might get the following error:
bash
 Task :csbyte-service:bootJar FAILED

FAILURE: Build failed with an exception.
This is due to the application trying to create the fat JAR file with the main class missing.
Let's replace the org.springframework.boot plugin with Spring’s explicit Bill of Materials (BOM) setup.
Remove the org.springframework.boot from plugin{} section.
bash
plugins {
	id 'java'
	id 'org.springframework.boot' version '3.5.14' // remove it
	id 'io.spring.dependency-management' version '1.1.7'
}
Add the following configuration
bash
ext {
	springBootVersion = '3.5.14'
}

dependencies {
	implementation platform("org.springframework.boot:spring-boot-dependencies:${springBootVersion}")
	
Make sure to use your own Spring Boot version.
Now, reload and sync the dependencies.

Build the library

bash
./gradlew build
Output:
bash
BUILD SUCCESSFUL in 3s
36 actionable tasks: 2 executed, 34 up-to-date

Importing the Library

Let's implement the library created in our applications. We can do it inside the dependencies section as below.
bash
dependencies {
	implementation project(':csbyte-service')
    ------
}
In this way, we can build the library which are common to application development so that it will be utilized in the application. This way, we can create a clean, maintainable, and enterprise-ready codebase structure.