Spring Boot - In-depth Principles - Customize starter

Posted by moe on Mon, 15 Jun 2020 21:25:55 +0200

2.2.3 Custom starter

Spring Boot is made up of many Starters (a series of starter plug-ins that are automatically configured), and it is also because of starter that Spring Boot is popular.

starter is a very important part of Spring Boot and can be understood as a pluggable plug-in because it allows developers who use a feature to ignore the processing of dependent libraries and do not need specific configuration information. Spring Boot automatically discovers the required beans through classpath classes and weaves them into the corresponding beans.

For example, if we need a Redis plug-in, we can use spring-boot-starter-data-redis, and if we need MongoDB, we can use spring-boot-starter-data-mongodb Why do I need to customize starter

During development, there are often configuration modules that are independent of the business.If we encapsulate these functional configurations outside of stand-alone business code as starter s, we only need to reuse them inPom.xmlReference to dependencies is sufficient, and Spring Boot helps us complete automatic assembly. Custom starter naming rules

The starter provided by Spring Boot is named after spring-boot-starter-xxxx and is officially recommended for custom starters

The xxxx-spring-boot-starter naming rules distinguish the starters provided by the Spring Boot ecology. Customization custom-spring-boot-starter
  1. New Maven project, named custom-spring-boot-starter, import dependencies

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  2. Writing JavaBean s

    @ConfigurationProperties(prefix = "custom")
    public class CustomBean {
       private Integer id;
       private String name;
       public Integer getId() {
           return id;
       public void setId(Integer id) {
           this.id = id;
       public String getName() {
           return name;
       public void setName(String name) {
           this.name = name;
  3. Write Configuration Class

    // Automatic configuration when a specified class exists under the classpath of the class path
    public class CustomConfig {
       public CustomBean customBean() {
           return new CustomBean();
  4. Create META-INF/under resources Spring.factories

    Note: META-INF directory andSpring.factoriesFile needs to be created manually

   site.luojie.custom.config.CustomConfig Using custom-spring-boot-starter
  1. Import custom starter dependencies

  2. Write a configuration file

  3. unit testing

    public class LearnApplicationTest {
       private CustomBean customBean;
       public void testCustomBean(){

Topics: Web Development Spring Maven Apache Redis