Deep Dive into Spring Boot Auto‑Configuration and How to Build a Custom Starter
This article explains the inner workings of Spring Boot’s @SpringBootApplication annotation, the loading of auto‑configuration classes from META‑INF/spring.factories, the refresh of the application context, the creation of the embedded Tomcat server, and demonstrates how to create a custom starter with configuration properties.
The post begins by examining the main class generated by Spring Boot’s @SpringBootApplication annotation, showing the generated Java code for the main method and the composite annotations that make up @SpringBootApplication such as @SpringBootConfiguration , @EnableAutoConfiguration , and @ComponentScan .
It then details how Spring Boot discovers auto‑configuration classes: the framework reads the META-INF/spring.factories file, loads the class names listed under EnableAutoConfiguration , and registers them as beans. The article walks through the source of AutoConfigurationImportSelector , the process of loading factory names, filtering and importing configuration classes, and how the SpringApplication run method prepares the environment, creates the application context, and refreshes it.
During the refresh, the AbstractApplicationContext.refresh() method prepares the bean factory, registers bean post‑processors, initializes message sources and event multicaster, and finally instantiates all non‑lazy singletons. The ServletWebServerApplicationContext subclass overrides onRefresh() to create the embedded web server, using a ServletWebServerFactory (e.g., TomcatServletWebServerFactory ) to obtain a WebServer instance.
The article also shows the implementation of TomcatServletWebServerFactory.getWebServer() , which builds a Tomcat instance, configures connectors, sets the base directory, and prepares the servlet context.
Finally, it demonstrates how to build a custom Spring Boot starter: a Maven module that depends on spring-boot-autoconfigure , defines a configuration properties class annotated with @ConfigurationProperties , provides an auto‑configuration class annotated with @Configuration , @ConditionalOnClass , and @EnableConfigurationProperties , and registers the starter in META-INF/spring.factories . The custom starter can then be used in other projects to inject a service bean whose behavior is driven by external configuration.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.