[Spring Boot] how to customize the Spring Boot Starter

This article introduces

We all know that the Spring Boot project consists of starters, such as web starters, redis starters and so on.
By introducing the corresponding starter through maven, we can perfectly use the integrated spring mvc or redis without configuration

So how do we customize a starter?

This article will show you how to use the auto configuration feature of SpringBoot to create your own Spring Boot Starter.

Suppose Toy needs to be integrated into the starter framework or class, and wants to be loaded into the Spring context for us to call when the application starts.

Some small partners may ask why they do this? Just declare Toy as a Spring bean.

The answer is definitely yes, but adhering to the principle of quick start of Spring Boot, we can use the integrated functions or features we want more quickly by introducing starter, just like Toy above.

Another example is mybatis, because we cannot modify the source code of mybatis. One way is to create a SqlSessionFactory bean on the method through @ Bean and use it in the Spring Boot application.

The second way is to complete the integration of mybatis by creating a starter and introducing the starter of mybatis where mybatis needs to be used.

When many projects need to integrate mybatis, the starter method will be faster and more efficient.

Project structure

The project is divided into two modules:

Toy sample app and toy spring boot starter

  • Toy sample app: demonstrates how to introduce a self created starter
  • Toy spring boot starter: starter module, which is used to build Toy Spring beans for demonstration projects

Code introduction

toy-spring-boot-starter

  • META-INF/spring.factories file

This file indicates the name of the automatically injected class, which will be initialized and loaded into the context when the Spring Boot application starts.

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
        cn.bugkit.toy.autoconfigure.ToyAutoConfiguration
  • ToyAutoConfiguration file

@The Configuration annotation indicates the Configuration class of Spring

@The EnableConfigurationProperties(ToyProperties.class) annotation specifies the property configuration class that needs to be used

package cn.bugkit.toy.autoconfigure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Configuration
@EnableConfigurationProperties(ToyProperties.class)
public class ToyAutoConfiguration {

    @Autowired
    private ToyProperties toyProperties;

    @Bean
    public Toy toy(){
        return new Toy(toyProperties.getName(),toyProperties.getPassword(), toyProperties.getWeight());
    }

}
  • ToyProperties file

This class declares that it needs to be from application The properties file reads the properties for the toy() method of the above file to build the required Toy object.

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Configuration
@ConfigurationProperties(prefix = "toy")
public class ToyProperties {
    private String name;
    private String password;
    private int weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }
}
  • Toy file

The showInfo() method we need is provided, which is specifically used in the toy sample app project

public class Toy {
    private String name;
    private String password;
    private int weight;

    public Toy(String name, String password, int weight) {
        this.name = name;
        this.password = password;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public void showInfo(){
        System.out.println("===================start==========================");
        System.out.println("Toy [ Name: " + name +", password: " + password +", weight: " + weight + " ]");
        System.out.println("===================end============================");
    }
}

Toy sample app project

This project is used to demonstrate how to use our own toy spring boot starter

  • pom file

The pom file is introduced into the jar of the starter project

 <dependency>
    <groupId>cn.bugkit</groupId>
    <artifactId>toy-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>
  • ToyService file

This class is injected into the Toy bean of the starter project, and the showInfo() method of Toy is invoked after the ToyService initialization is completed.

package cn.bugkit.toy.app.service;

import cn.bugkit.toy.autoconfigure.Toy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author bugkit
 * @since 2022.2.24
 */
@Service
public class ToyService {

    @Autowired
    private Toy toy;

    @PostConstruct
    public void init() {
        toy.showInfo();
    }

}
  • application.properties file

The key of this file (such as toy.name) corresponds to the ToyProperties class of the starter project.

toy.name=Hello Kitty
toy.password=kitty@1234
toy.weight=99
  • Console startup log

    .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
    '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::                (v2.6.3)
    
    2022-02-24 14:53:24.092  INFO 14652 --- [           main] c.bugkit.toy.app.StarterDemoApplication  : Starting StarterDemoApplication using Java 1.8.0_211 on Bennetty74 with PID 14652 (E:\ideaProjects\spring-learning\toy-sample-app\target\classes started by Bennetty74 in E:\ideaProjects\spring-learning)
    2022-02-24 14:53:24.092  INFO 14652 --- [           main] c.bugkit.toy.app.StarterDemoApplication  : No active profile set, falling back to default profiles: default
    ===================start==========================
    Toy [ Name: Hello Kitty, password: kitty@1234, weight: 99 ]
    ===================end============================
    2022-02-24 14:53:24.608  INFO 14652 --- [           main] c.bugkit.toy.app.StarterDemoApplication  : Started StarterDemoApplication in 0.888 seconds (JVM running for 1.836)
    
    Process finished with exit code 0

summary

  • Toy Spring Boot starter: we integrate toy through the auto configuration feature of Spring Boot
  • Toy sample app: introduce the maven dependency of the starter where the starter needs to be used, so that the Spring Bean corresponding to toy can be used

Optional

You can check the source code of Github warehouse for the remaining code, which will not be repeated here.

Code address: https://github.com/bennetty74...

Keywords: Java Spring Spring Boot

Added by lailaigogo on Thu, 24 Feb 2022 12:46:43 +0200