Open In App

Spring Boot - Customizing Spring Boot Starter

Last Updated : 25 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Maven Build Success

Project Structure

After creating the project successfully, the folder structure will look like the below image:

Project Folder Structure

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:

Maven Install

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:

Maven Build Success

Project Structure

After the project created successfully, the project structure will look like the below image:

Project Folder Structure

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:

Console 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.


Next Article

Similar Reads