Write spring boot starter from scratch

Time:2020-4-29

Spring boot provides convenience for developers.
This article describes how to write starter so that developers can reuse their own or project group’s code.

Code download address: https://gitee.com/jxd134/spring-boot-greeter-starter.git

1 new project

The project is built on Maven and consists of the following three modules:

  • Greeter Library: encapsulation tool class;
  • Greeter spring boot autoconfigure: complete automatic configuration;
  • Greeter spring boot starter: provided to users

Main projectpom.xmlThe contents in are as follows (some contents are omitted):

org.example
    spring-boot-custom-starter
    0.0.1-SNAPSHOT
    pom

    
        greeter-library
        greeter-spring-boot-autoconfigure
        greeter-spring-boot-starter
    

    
        
            org.springframework.boot
            spring-boot
            2.2.5.RELEASE
            compile
        
    

    
        1.8
        UTF-8
        3.8.0

Note that the packaging method in the parent project needs to be set topom, in additionSpring BootThe version shall be clear (it can be determined according to the regulations of the project team)

2 tool class (greeter Library)

projectpom.xmlThe contents in are as follows (some contents are omitted):

spring-boot-custom-starter
        org.example
        0.0.1-SNAPSHOT
    
    greeter-library
    greeter-library
    0.0.1-SNAPSHOT

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                ${maven-compiler-plugin.version}
                
                    8
                    8

Create a sample project launch welcome code here (for example only):

public String greet(LocalDateTime localDateTime) {

        String name = greetingConfig.getProperty(USER_NAME);
        int hourOfDay = localDateTime.getHour();

        if (hourOfDay >= 5 && hourOfDay < 12) {
            return String.format("Hello %s, %s", name, greetingConfig.get(MORNING_MESSAGE));
        } else if (hourOfDay >= 12 && hourOfDay < 17) {
            return String.format("Hello %s, %s", name, greetingConfig.get(AFTERNOON_MESSAGE));
        } else if (hourOfDay >= 17 && hourOfDay < 20) {
            return String.format("Hello %s, %s", name, greetingConfig.get(EVENING_MESSAGE));
        } else {
            return String.format("Hello %s, %s", name, greetingConfig.get(NIGHT_MESSAGE));
        }
    }

    public String greet() {
        return greet(LocalDateTime.now());
    }

Here, the basic completion of tool module code

3. Automatic configuration (greeter spring boot autoconfigure)

3.1 configuration principle

The tool class has finished encapsulation. At this time, you need to complete the automatic configuration code writing of the tool class.
When the spring boot project starts, it will scan thespring.factoriesFile (located inMETA-INFFolder), and load the corresponding configuration class under classpath according to the configuration information.

Here, tospring.boot.autoconfigureDependentspring.factoriesAs an example:

Write spring boot starter from scratch

spring.factoriesIn the file, the automation configuration depends on the following:

Write spring boot starter from scratch

3.2 create configuration class

The configuration class code is as follows:

@ConfigurationProperties(prefix = "greeter")
public class GreeterProperties {

    private String userName;
    private String morningMessage;
    private String afternoonMessage;
    private String eveningMessage;
    private String nightMessage;

    //Omit get / set function
}

@Configuration
@ConditionalOnClass(Greeter.class)
@EnableConfigurationProperties(GreeterProperties.class)
public class GreeterAutoConfiguration {

    @Autowired
    private GreeterProperties greeterProperties;

    @Bean
    @ConditionalOnMissingBean
    public GreetingConfig greeterConfig() {

        String userName = greeterProperties.getUserName() == null ? System.getProperty("user.name") : greeterProperties.getUserName();
        String morningMessage = greeterProperties.getMorningMessage() == null ? "Good Morning" : greeterProperties.getMorningMessage();
        String afternoonMessage = greeterProperties.getAfternoonMessage() == null ? "Good Afternoon" : greeterProperties.getAfternoonMessage();
        String eveningMessage = greeterProperties.getEveningMessage() == null ? "Good Evening" : greeterProperties.getEveningMessage();
        String nightMessage = greeterProperties.getNightMessage() == null ? "Good Night" : greeterProperties.getNightMessage();

        GreetingConfig greetingConfig = new GreetingConfig();
        greetingConfig.put(USER_NAME, userName);
        greetingConfig.put(MORNING_MESSAGE, morningMessage);
        greetingConfig.put(AFTERNOON_MESSAGE, afternoonMessage);
        greetingConfig.put(EVENING_MESSAGE, eveningMessage);
        greetingConfig.put(NIGHT_MESSAGE, nightMessage);
        return greetingConfig;
    }

    @Bean
    @ConditionalOnMissingBean
    public Greeter greeter(GreetingConfig greetingConfig) {
        return new Greeter(greetingConfig);
    }
}

The above is the main code of the module, which is mainly divided into configuration information class and automatic configuration class:

  1. Greeterproperties: read configuration information from the project configuration file, useConfigurationPropertiesRead prefix isgreeterConfiguration information of;
  2. Greeterautoconfiguration: depends on the greeter class. When the greeter class is loaded,SpringWill loadGreeterAutoConfigurationBean defined in.

Conditionalonmissingbean: decorated bean, ifIOCIf it does not exist in, it will be loaded toIOC

3.3 configuration file

META-INFAdd in folderspring.factoriesFile, fill in the fully qualified name of the automation configuration class, as follows:

org.springframework.boot.com.example.greeter.autoconfigure.EnableAutoConfiguration=\
com.example.greeter.autoconfigure.GreeterAutoConfiguration

4. Starter (greeter spring boot starter)

The current module only needs to be addedpom.xml, you can perfectly present the starter to the user:

spring-boot-custom-starter
        org.example
        0.0.1-SNAPSHOT
    

    greeter-spring-boot-starter
    0.0.1-SNAPSHOT
    greeter-spring-boot-starter

    
        UTF-8
        0.0.1-SNAPSHOT
        2.2.5.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter
            ${spring-boot.version}
        
        
            org.example
            greeter-spring-boot-autoconfigure
            ${greeter.version}
        
        
            org.example
            greeter-library
            ${greeter.version}
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                ${maven-compiler-plugin.version}
                
                    ${java.version}
                    ${java.version}

Introduce spring boot dependency, as well as encapsulation tool module and automation configuration module (current module is similar to agent).
implementmvn installAfter the order,starterRelevant jar packages are stored in Maven local warehouse for users to use.

Because of the need to pack, so the introduction ofmaven-compiler-plugin

5 example

The example is simple and only needs to bepom.xmlThe import dependency in the file is as follows:

org.example
            greeter-spring-boot-starter
            0.0.1-SNAPSHOT

You can introduce a self-made starter (note that the spring boot version number of the starter matches).

This article refers tohttps://www.baeldung.com/spring-boot-custom-starterOne article.
PS:
If you think my article is helpful to you, please pay attention to my WeChat official account. Thank you!
程序员打怪之路