SoFunction
Updated on 2025-04-22

Spring Boot Starter Full Analysis of the Principle of Automatic Assembly

The core design philosophy of Spring Boot Starter isConventions are better than configuration, its core implementation is based onAuto-ConfigurationandConditional Registration. The following is its effectiveness principle:

Consent is greater than configuration

Reduce the steps that developers need to manually configure by predefined reasonable default behavior and specifications. A more significant change is to reduce XML configuration. Some actual manifestations are as follows:

  • Project Structure Agreement
    • Default directory structure:likesrc/main/javaStore code,src/main/resourcesStore configuration files.
    • Configuration file namingorIt is automatically loaded without explicitly specifying the path.
  • Auto-Configuration
    • Conditional Bean Registration: Depends according to classpath (if presentDataSourcekind)Automatically configure database connection pool
    • Default parameter value: For example, the default port of embedded Tomcat is8080, no manual specification is required.
  • Starter dependency
    • Depend on aggregation:Introducedspring-boot-starter-webThat is, it automatically contains all dependencies required for web development (such as Tomcat, Jackson, Spring MVC).
    • Use out of the box: No need to manually manage version compatibility.
  • RESTful routing mapping
    • Annotation driver:pass@GetMapping("/path")The interface can be defined without configuring routing rules in XML.

Automatic configuration mechanism

Triggering phase: @EnableAutoConfiguration

  • When the application starts,@SpringBootApplicationCombined@EnableAutoConfiguration, trigger the automatic configuration process.
  • AutoConfigurationImportSelectorCalled, responsible for loading all candidate automatic configuration classes.
public String[] selectImports(AnnotationMetadata metadata) {
  // 1. Load all candidate automatic configuration classes  List<String> configurations = getCandidateConfigurations();
  // 2. Deduplication, filtering, sorting  configurations = removeDuplicates(configurations);
  configurations = filter(configurations, autoConfigurationMetadata);
  return (new String[0]);
}

Loading and filtering:

  • Load all candidate configuration classes

From allMETA-INF/Read in the fileEnableAutoConfigurationCorresponding configuration class. In Spring Boot, the automatic configuration class is loaded from , and the ImportCandidates class is introduced to handle this change.

  • Deduplication and filtering

Remove duplicate configuration classes and pass conditional annotations (e.g.@ConditionalOnClass ,@ConditionalOnMissingBean) Selectively retain the configuration class of the current environment.

  • @ConditionalOnClass: Effective when the classpath has a specified class
  • @ConditionalOnMissingBean: Effective if no specified bean exists in the container
  • @ConditionalOnProperty: Take effect when configuration properties match

Sort

according to@AutoConfigureOrderor@AutoConfigureAfterAdjust the loading order of configuration classes.

Bean Register

  • The filtered automatic configuration class is parsed into standard@Configurationkind.
  • In each configuration class@BeanMethod dynamically registers beans to Spring containers based on condition annotations.

Write a custom Spring Boot Starter

Project Structure Planning

It is recommended to be divided into two modules:

  • Automatic configuration module: Contains core logic and automatic configuration classes (such ashello-spring-boot-autoconfigure)。
  • Starter module: Empty project, only as dependency aggregation (e.g.hello-spring-boot-starter)。
hello-spring-boot-starter-parent(fatherPOM)
├── hello-spring-boot-autoconfigure(Automatic configuration module)
└── hello-spring-boot-starter(StarterModule)
hello-spring-boot-starter/
├── hello-spring-boot-autoconfigure/
│   ├── src/
│   │   ├── main/
│   │   │   ├── java/com/example/autoconfigure/
│   │   │   │   ├── 
│   │   │   │   ├── 
│   │   │   │   └── 
│   │   │   └── resources/
│   │   │       └── META-INF/
│   │   │           └── 
│   │   └── test/
│   └── 
├── hello-spring-boot-starter/
│   └── 
└── 

Create an automatic configuration module (hello-spring-boot-autoconfigure)

Add Maven dependencies

<!--  -->
<dependencies>
    <!-- Spring Boot Automatically configure basic dependencies -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
        <version>3.1.5</version>
    </dependency>
    <!-- Optional:Configuration property processing -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <version>3.1.5</version>
        <optional>true</optional>
    </dependency>
</dependencies>

Define core service classes

public class HelloService {
    private String message = "Hello, World!";  // Default message    public String sayHello() {
        return message;
    }
    // Getter and Setter are used to modify message through configuration    public String getMessage() { return message; }
    public void setMessage(String message) {  = message; }
}

Define configuration property class (optional)

@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
    private String message = "Hello, World!";
    // Getter and Setter    public String getMessage() { return message; }
    public void setMessage(String message) {  = message; }
}

Write automatic configuration classes

@Configuration
@EnableConfigurationProperties()  // Enable configuration properties@ConditionalOnClass()  // When HelloService takes effect on classpathpublic class HelloAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean  // Take effect when the user does not customize HelloService    public HelloService helloService(HelloProperties properties) {
        HelloService service = new HelloService();
        (());
        return service;
    }
}

Register automatic configuration

existresources/META-INF/Created belowdocument:

=\

Create a Starter module (hello-spring-boot-starter)

Add Maven dependencies

<!--  -->
<dependencies>
    <!-- Introducing automatic configuration module -->
    <dependency>
        <groupId></groupId>
        <artifactId>hello-spring-boot-autoconfigure</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>

Use a custom Starter

Introducing Starter dependencies in applications

<!-- User project -->
<dependency>
    <groupId></groupId>
    <artifactId>hello-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

Inject Beans into the code

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/hello")
    public String hello() {
        return ();
    }
}

Custom configuration (optional)

existModify the message:

=Hello, Spring Boot!

This is the end of this article about the principle of Spring Boot Starter automatic assembly. For more related Spring Boot Starter automatic assembly content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!