The labs on this site need JavaScript to run. The same content is written out below.
Learn › Spring › Spring Boot
Spring Boot auto-configuration
Why do beans appear when all you did was add a dependency?
Why it exists — With Spring alone, you had to register beans such as DataSource, EntityManagerFactory, and the transaction manager yourself in configuration classes or XML, and register the DispatcherServlet yourself in a place such as web.xml, so every project repeated almost the same configuration. Spring Boot's auto-configuration prepares this configuration in advance on the library side and applies it only when its conditions are met, so developers register by hand only the parts they want to change.
Where it's used today — Every application annotated with @SpringBootApplication receives its default beans through this feature. Once you add a starter and write only the database connection URL and account, the connection pool, JPA, and embedded Tomcat are ready, and anything you want to differ from the defaults you change with settings in application.yml or by registering beans such as DataSource and JsonMapper yourself with @Bean. When you build an in-house library shared by several projects, you sometimes write your own auto-configuration for it.
When an application starts, Spring Boot goes through a set of configuration classes prepared in advance, one by one, and decides "if this condition is met, register this bean". The conditions are mainly which libraries are on the classpath and whether the developer has registered the same bean.
Checked against real execution · The configurations on the screen (a classpath with only the jars of the starters, application.yml, MyConfig) were started with Spring Boot 4.1.1 using --debug, and all 64 combinations were checked against the condition evaluation report and the registered beans (MySQL 8.4.11)
Concepts in this lab
- Spring Boot auto-configuration
- This Spring Boot feature looks at the libraries on the classpath and at the configuration values, and automatically registers the beans that are needed. For example, if a JDBC driver and connection details are present, it configures a DataSource automatically. Each auto-configuration has conditions for when it applies, and if the developer registers a bean of the same kind directly, the part of the auto-configuration that creates that bean does not apply.
- Starter
- Where it's used today — For a new project, you start by choosing starters such as web, data-jpa, and security at start.spring.io. Spring Boot manages the versions, so you usually do not write a version on a starter.
- This is a Spring Boot set of dependencies that groups the libraries needed for a particular feature in versions that are compatible with each other. Adding just the web one (spring-boot-starter-web up to Spring Boot 3, spring-boot-starter-webmvc since Spring Boot 4) brings in Spring MVC, JSON processing, embedded Tomcat, and more. It saves you the work of resolving version conflicts between libraries yourself.
- Embedded server
- Where it's used today — It suits deployment where a single jar file is made into a Docker image and run, and you change the port with the server.port setting. You can also switch to Jetty instead of the default, Tomcat.
- This is a web server (Tomcat by default) that is included inside a Spring Boot application and runs together with it. You can run the application with a single java -jar command, without the steps of installing a server separately and deploying the application to it.
- @Configuration and @Bean
- Why it exists — XML configuration writes class names as text, so a typo or a type error was found only by running the application. @Configuration and @Bean let you write bean definitions in Java code, so the compiler checks them and you can jump to them directly in the IDE.
- Where it's used today — They are used to register library objects that must be created with configuration values, such as ObjectMapper and RestClient, and configuration objects such as Spring Security's SecurityFilterChain.
- @Configuration marks a configuration class that contains bean definitions, and the object returned by each @Bean method inside it is registered as a bean. Use them when you need to make a bean from a class in an external library that you cannot modify, or when you need to control the creation process yourself. Classes that you write yourself are usually registered with @Component or a related annotation.
- Component scanning
- Why it exists — If you register beans one by one with XML or @Bean methods for each class, the registration list must also be changed every time you create a class. Component scanning lets Spring find and register classes when you only put an annotation on them.
- Where it's used today — Services, repositories, and controllers that you write yourself are usually registered this way. So you place the @SpringBootApplication class in the topmost package of the project, and to make scanning reach other packages, you specify them with the scanBasePackages attribute.
- This feature finds the classes under a given package that carry @Component or one of its related annotations (such as @Service, @Repository, and @Controller) and registers them as beans automatically. In Spring Boot, the default target is the package of the class annotated with @SpringBootApplication and its subpackages.
Try these
- Default settings — The web and JPA starters. All the beans that are needed are created, and you register none yourself.
- Leaving out the database URL — The driver is MySQL, but there is no connection URL. Startup fails.
- With H2, even without a URL — When Spring Boot finds an embedded database, it creates an in-memory database for you.
- Registering your own DataSource — The auto-configuration backs away, and the one you created is used.
- Registering your own JsonMapper — The JsonMapper that Spring Boot would have created is not registered.
- Removing the web starter — Neither Tomcat nor DispatcherServlet is created.
Running with the default settings
- The application starts. The @EnableAutoConfiguration on @SpringBootApplication gathers and loads the lists of auto-configuration classes written in each Spring Boot jar on the classpath. Spring Boot 4 splits auto-configuration into a module (jar) per technology, so the auto-configuration of a technology enters the list only when you add its dependency. Your own @Configuration and @Component classes are registered first, and then the conditions of the auto-configurations are evaluated one by one.
- Embedded server auto-configuration: The web starter brought in the Tomcat library with it. Tomcat is on the classpath, so Spring Boot registers the bean that starts an embedded Tomcat. That is why the application runs from a single jar, with no separate application server to install.
- Spring MVC auto-configuration: The DispatcherServlet class is present, so Spring Boot registers DispatcherServlet and the default MVC components (message converters, handler mappings, and so on).
- Jackson auto-configuration: You have not registered a JsonMapper yourself, so a JsonMapper with the default settings is registered.
- DataSource auto-configuration: The spring-jdbc classes are present, and you have not registered a DataSource yourself. Spring Boot creates a HikariCP connection pool with the connection information from the settings and registers it.
- JPA auto-configuration: It uses the DataSource prepared earlier to register an EntityManagerFactory and a transaction manager for JPA. Auto-configurations also have an order among themselves, so this one is evaluated after the DataSource is ready.
- Spring Data JPA auto-configuration: It finds the interfaces that extend JpaRepository, creates an implementation object for each of them, and registers it as a bean.
- The remaining auto-configurations: Even when they are in the list, they are skipped if their conditions are not met. For example, the JMX auto-configuration applies only when spring.jmx.enabled is turned on, so it is left out with the default settings. In Spring Boot 4, the auto-configurations for technologies whose dependencies you did not add, such as Redis or Kafka, are not in the list at all.
Result of this run
- Two conditions often found on auto-configurations are whether the library is on the classpath (@ConditionalOnClass), and whether the developer has already registered a bean of the same type (@ConditionalOnMissingBean). There are also conditions that look at settings (@ConditionalOnBooleanProperty and others). A starter brings in the set of libraries that are needed all at once, which satisfies the first condition, and in Spring Boot 4 it also brings in the auto-configuration module of that technology.
- An auto-configuration with such a condition (@ConditionalOnMissingBean) backs away when you register a bean of the same type yourself. Start with the defaults, and register yourself only the parts that you want to change. To see which auto-configurations were applied or left out, and why, run the application with the --debug option, which prints a conditions report.
Code
// build.gradle
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.mysql:mysql-connector-j'
}
# application.yml
spring.datasource.url: jdbc:mysql://localhost:3306/shop
spring.datasource.username: shop
spring.datasource.password: shop1234
// Conditions on DataSourceAutoConfiguration (only the relevant parts kept)
// @ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
// DataSource is in the JDK, so this really checks for spring-jdbc
// @ConditionalOnMissingBean({DataSource.class, XADataSource.class})
// pool only when you registered no DataSource (on a nested class)
Assumptions of this model
This lab picks only a few representative auto-configurations and simplifies them. The real class names and conditions are more fine-grained (for example, DataSourceAutoConfiguration, JacksonAutoConfiguration, HibernateJpaAutoConfiguration). All 64 combinations were actually started as a Spring Boot 4.1.1 application and checked. The classpath was built from only the jars that the dependencies (starters) on the screen bring in (the list was computed from the POMs published on Maven Central), the application.yml and MyConfig on the screen were put in as they are, and the application was run with the --debug option. Then the condition evaluation report, the registered beans (and which configuration class created each), the database actually connected through the DataSource, the response on port 8080, and the startup failure message were compared line by line with the condition evaluation table on the screen. Combinations whose code on the screen is the same (they differ only in hidden settings) are the same program, so each was run once, which makes 27 configurations. For MySQL, the application connected to a MySQL 8.4.11 container with the URL (localhost:3306/shop) and the example account on the screen as they are, and the runtime environment is a Linux container with Java 21. What was added without being on the screen is the main class (@SpringBootApplication) and, in the JPA configurations, one example entity and one example repository that extends JpaRepository. It was confirmed that with MySQL, if you write only the connection URL and leave out the account, Hibernate cannot connect to the database and startup fails ("Unable to determine Dialect without JDBC metadata"). That is why the MySQL settings on the screen include the account. H2 connects with the URL alone. It was also confirmed that when the DataSource you register yourself has a URL different from the one in application.yml, the connection goes to the URL of the one you registered. There were 12 auto-configuration candidates with only the starter, 30 with the web starter added, 30 with the JPA starter and a driver added, and 48 with both added (Spring Boot 4 keeps auto-configurations in modules split by technology). The conditions in the condition evaluation table, the DataSource auto-configuration conditions in the code panel, the reason the JMX auto-configuration is left out (spring.jmx.enabled), and the fact that the JPA auto-configuration is evaluated after the DataSource auto-configuration were also confirmed from the run results. The dependency names are those of Spring Boot 4 (up to Spring Boot 3, the web starter was named spring-boot-starter-web). The numbers in the result table count rows of the condition evaluation table on the screen, and far more beans are actually registered.
Previous lab: REST APIs and message converters · Next lab: Configuration precedence