Spring Boot - Customizing Spring Boot Starter
Last Updated :
25 Sep, 2024
Spring Boot Starters are specialized project types designed to encapsulate and distribute common functionality, simplifying the setup of Spring Boot applications. Official starters, like spring-boot-starter-web
and spring-boot-starter-data-jpa
, bundle dependencies, configurations, and pre-built beans for specific use cases.
Creating a custom Spring Boot Starter allows you to bundle specific features (like logging, security, or common service configurations) into a reusable component, which is particularly useful for larger projects that require shared logic across multiple services or microservices.
What is a Spring Boot Starter?
A Spring Boot Starter is essentially a pre-configured template of dependencies, configurations, and functionalities that can be quickly added to a project. Spring Boot provides numerous built-in starters for common use cases:
- spring-boot-starter-web: Provides web functionalities for REST APIs using Spring MVC.
- spring-boot-starter-data-jpa: Simplifies database interactions using JPA and Hibernate.
These starters help developers quickly set up Spring Boot projects by reducing boilerplate configurations. However, when specific shared functionalities are needed, custom Spring Boot Starters become essential.
Why Create a Custom Spring Boot Starter?
In large projects or microservices architectures where shared business logic is present across multiple applications, creating a custom Spring Boot Starter can help avoid code duplication and repetitive configuration. For example, a custom starter can encapsulate:
- Centralized logging
- Custom security filters
- Predefined beans for common services (e.g., custom database connections or APIs)
- Configuration and validation logic
With a custom starter, all necessary components can be bundled into a single module (JAR file) that can be easily integrated by adding the starter dependency in the pom.xml
.
Key Components of a Custom Spring Boot Starter
1. Auto-Configuration
Auto-configuration is the process by which Spring Boot automatically configures beans and services based on the presence of specific dependencies or properties. This reduces the need for manual bean configuration.
Java
package com.example.starter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // Indicates that this class provides Spring configuration
public class CustomAutoConfiguration {
// Method to create a custom bean with properties from CustomProperties
@Bean
public String customBean(CustomProperties properties) {
return "Custom Bean: " + properties.getMessage(); // Returns custom message
}
}
2. Configuration Properties
Custom Spring Boot starters can define customizable properties. For instance, a logger starter might allow users to specify the log level via the application.properties
file using the @ConfigurationProperties
annotation.
Java
package com.example.starter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "custom") // Binds properties prefixed with 'custom'
public class CustomProperties {
private String message = "Default Message"; // Default message property
// Getter for the message property
public String getMessage() {
return message;
}
// Setter for the message property
public void setMessage(String message) {
this.message = message;
}
}
3. Bean Definitions
Spring Boot automatically registers beans defined in the starter's configuration classes. These beans can be services or utility classes reused across applications.
Java
package com.example.starter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // Indicates that this class provides Spring configuration
public class CustomStarterConfig {
// Method to create a custom message bean using CustomProperties
@Bean
public String customMessageBean(CustomProperties customProperties) {
return customProperties.getMessage(); // Returns the message from properties
}
}
4. spring.factories File
To register the starter's auto-configuration classes, include them in the META-INF/spring.factories
file.
# Auto-configuration classes for Spring Boot to load
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.starter.CustomAutoConfiguration
Implementation of a Custom Spring Boot Starter
File Structure Setup
Here's a sample file structure for the custom Spring Boot Starter project:
custom-spring-boot-starter
│
├── custom-spring-boot-starter
│ ├── src
│ │ └── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ ├── starter
│ │ │ │ ├── CustomProperties.java
│ │ │ │ └── CustomAutoConfiguration.java
│ │ │ └── CustomStarterApplication.java
│ │ └── resources
│ │ └── META-INF
│ │ └── spring.factories
│ └── pom.xml
│
└── demo-application
├── src
│ └── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ └── DemoApplication.java
│ └── resources
└── pom.xml
Step-by-Step Implementation to Create Custom Spring Boot Starter
Step 1: Create the Maven Project
Create a new Maven project using below command:
mvn archetype:generate -DgroupId=com.example -DartifactId=custom-spring-boot-starter -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Output:
Project Structure
After creating the project successfully, the folder structure will look like the below image:
Step 2: Update pom.xml
Add the necessary dependencies for auto-configuration:
pom.xml:
XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>custom-spring-boot-starter</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>custom-spring-boot-starter</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>3.3.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.3.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Step 3: Create the CustomProperties Class
This class holds the properties that can be customized through the application properties file.
Java
package com.example.starter;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "custom") // Binds properties prefixed with 'custom'
public class CustomProperties {
private String message = "Default Message"; // Default message property
// Getter for the message property
public String getMessage() {
return message;
}
// Setter for the message property
public void setMessage(String message) {
this.message = message;
}
}
Step 4: Create the CustomAutoConfiguration Class
This class defines the beans that will be automatically configured when the starter is included in an application.
Java
package com.example.starter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // Indicates that this class provides Spring configuration
public class CustomAutoConfiguration {
// Method to create a custom bean using properties from CustomProperties
@Bean
public String customBean(CustomProperties properties) {
return "Custom Bean: " + properties.getMessage(); // Returns custom message
}
}
Step 5: Create the Spring Factories file
Create this file in src/main/resources/META-INF/
to register the auto-configuration class.
spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.CustomAutoConfiguration
Install Maven
mvn clean install
Output:
Setup the Demo Application
Step 1: Create a New Maven Project
Create another Maven project for the demo application where you will use the custom starter.
mvn archetype:generate -DgroupId=com.example -DartifactId=demo-application -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Output:
Project Structure
After the project created successfully, the project structure will look like the below image:
Step 2: Update the pom.xml
Include the custom starter dependency:
<dependency>
<groupId>com.example</groupId>
<artifactId>custom-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
pom.xml:
XML
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo-application</artifactId>
<version>1.0-SNAPSHOT</version>
<name>demo-application</name>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>3.3.4</version> <!-- Spring Boot starter dependency -->
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>custom-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version> <!-- Your custom starter dependency -->
</dependency>
</dependencies>
</project>
Step 3: Create the DemoApplication Class
This is the main entry point for your Spring Boot application.
Java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
@EnableConfigurationProperties(CustomProperties.class)
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
}
}
Step 4: Create the DemoApplicationRunner Class
Java
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class DemoApplicationRunner implements CommandLineRunner {
private final CustomProperties customProperties;
@Autowired
public DemoApplicationRunner(CustomProperties customProperties) {
this.customProperties = customProperties;
}
@Override
public void run(String... args) throws Exception {
System.out.println("Custom Message: " + customProperties.getMessage());
}
}
Step 5: Update application.properties
Set the custom properties in the src/main/resources/application.properties file.
custom.message=Hello from Custom Starter! // Custom message property
Step 6: Run the application
Once the setup is complete, you can run the demo application.
This value will now be injected into the CustomProperties class and when you can run the application, we should see:
Custom Message: Hello from Custom Starter!
Output:
Conclusion
This article covered how to create and customize the Spring Boot starter, bundle the common configurations, and inject the reusable beans across the multiple projects. We also learned how to configure the properties to allow the dynamic customization and override the default settings via the application.properties file.
By following this article, we can create the own custom Spring Boot starter to simplify and streamline the microservice or multi-project step.
Similar Reads
Customizing Spring Boot Banner and Startup Logs
Spring Boot displays a default banner in the console or log file when the application starts. While this default banner is simple and informative, you can customize it to include your own text, logo, or both. Additionally, Spring Boot allows you to customize startup logs to include specific informat
6 min read
Spring Boot - Getting Started
Spring Boot is a part of the larger Spring Framework ecosystem which is known for its comprehensive programming and configuration model for the modern Java-based enterprise applications. Spring Boot has emerged as a go-to framework for creating REST APIs, microservices, and web applications with les
5 min read
Spring Boot 3 - Creating a Custom Starter
Starters are an integral part of the Spring Boot application. In addition to dependency versioning, they provide the ability to describe the configuration for a particular functionality. They gained their popularity due to the development of microservice architecture. When we have dozens or hundreds
3 min read
Spring Boot - Starter Parent
Spring Boot Starter Parent is a starter project that provides the default configuration for spring-based applications. It is added as a parent in the pom.xml file. The spring-boot-starter-parent defines spring-boot-dependencies as its parent. The spring-boot-starter-parent inherits dependency manage
3 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight natu
8 min read
Spring Boot â Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code.In this article, we will guide you through set
4 min read
Spring Boot â Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requ
5 min read
Spring Boot â Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate diffe
5 min read
Spring Boot - Customize Whitelabel Error Page
In the Spring Boot ecosystem, when there is no custom error page to handle a specific error, Spring Boot by default handles the error with the help of the Whitelabel error page. This is the default Whitelabel error page. We can also customize this whitelabel error page. In this article, let us discu
4 min read
Spring Boot - Consuming and Producing JSON
Spring Boot is one of the famous frameworks for developing web applications and this framework provides a lot of features like auto-configuration, Spring Integration, Dependency management, and other features are available in Spring Boot framework. In this article, we will explain Spring Boot Consum
3 min read