Skip to lesson

Auto-configuration and @SpringBootApplication

A web app needs a server, a JSON converter and a database pool, and nobody wants to create them again in every project. Yet your own settings must still win when they differ from the defaults.

@SpringBootApplication: three annotations in one

@SpringBootApplication is a shortcut for three annotations on the main class: @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan.

The boot-lab main class written with the three annotations that @SpringBootApplication stands for.

Two sources fill the application context. Component scanning finds your classes marked @Component, @Service or @RestController in the main class package and below.

Example 1 · BootLabApplication.java, JsonCheckRunner.java

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
// src/main/java/com/shoplite/lab/BootLabApplication.javapackage com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.SpringBootConfiguration;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.annotation.ComponentScan;
// The same as @SpringBootApplication, written out in full@SpringBootConfiguration@EnableAutoConfiguration@ComponentScanpublic class BootLabApplication {
    public static void main(String[] args) {        SpringApplication.run(BootLabApplication.class, args);    }}
// src/main/java/com/shoplite/lab/JsonCheckRunner.javapackage com.shoplite.lab;
import java.math.BigDecimal;import java.time.LocalDate;import java.util.Map;
import org.springframework.boot.CommandLineRunner;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
@Componentpublic class JsonCheckRunner implements CommandLineRunner {
    record Product(String name, BigDecimal price, LocalDate addedOn) { }
    private final JsonMapper jsonMapper;    private final ApplicationContext context;
    public JsonCheckRunner(JsonMapper jsonMapper, ApplicationContext context) {        this.jsonMapper = jsonMapper;        this.context = context;    }
    @Override    public void run(String... args) {        Map<String, JsonMapper> mappers = context.getBeansOfType(JsonMapper.class);        System.out.println("JsonMapper beans: " + mappers.keySet());        Product notebook = new Product("A4 notebook", new BigDecimal("45.50"), LocalDate.of(2026, 7, 1));        System.out.println(jsonMapper.writeValueAsString(notebook));    }}
Output
JsonMapper beans: [jacksonJsonMapper]
{"name":"A4 notebook","price":45.50,"addedOn":"2026-07-01"}

What this code does

  • The main class uses the three annotations instead of @SpringBootApplication, and the app behaves the same. Put @SpringBootApplication back afterwards: it is shorter and its scan also skips a few internal classes.
  • Nobody in boot-lab wrote a JsonMapper (Jackson's JSON converter), yet the runner receives one. Auto-configuration created it as the bean jacksonJsonMapper, because Jackson is on the class path.
  • Boot's mapper writes 45.50 as a number and the LocalDate as "2026-07-01", the ISO date format that APIs use.

@SpringBootConfiguration marks this class as a configuration class, @EnableAutoConfiguration lets Boot add beans for the libraries it finds, and @ComponentScan finds @Component classes in this package and below. Component scanning finds your beans; auto-configuration adds Boot's beans. Knowing the three parts tells you where to look when a bean is missing or extra.

For Examples 1 to 3, add two lines to boot-lab's application.properties: spring.main.banner-mode=off and logging.level.root=warn. They hide the banner and the INFO log, so the console shows what the code prints. The Startup log lesson explains them.

Interview angle: "What does @SpringBootApplication do?" Name the three annotations and say in one line what each does.

Conditions: @ConditionalOnClass and @ConditionalOnMissingBean

Auto-configuration is a set of ordinary @Configuration classes inside Boot's jars, each guarded by conditions, that create beans such as the web server and the database pool only when their libraries are present.

A simplified sketch of Boot's Jackson auto-configuration: one condition on the class path, one on your own beans.

JacksonAutoConfiguration.javaJava
// Simplified sketch of Boot's JacksonAutoConfiguration@AutoConfiguration@ConditionalOnClass(JsonMapper.class)          // only if Jackson 3 is on the class pathpublic class JacksonAutoConfiguration {
    @Bean    @ConditionalOnMissingBean                  // only if you have no JsonMapper bean    JsonMapper jacksonJsonMapper(JsonMapper.Builder builder) {        return builder.build();    }}

Boot lists these classes in a file in each jar, META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports, and evaluates every one at startup. Two conditions do most of the work: @ConditionalOnClass creates the beans only if a library class is on the class path (Jackson's configuration needs JsonMapper, the pool configuration needs HikariDataSource), and @ConditionalOnMissingBean creates a bean only if you have not defined one of that type yourself.

Others you will meet: @ConditionalOnProperty (a setting has a value) and @ConditionalOnSingleCandidate (exactly one bean of a type exists).

This is why adding a starter changes behaviour: the starter puts classes on the class path, and @ConditionalOnClass conditions start to match.

Defining your own bean and watching Boot back off

Backing off is what an auto-configured bean does when you define your own bean of the same type: Boot's @ConditionalOnMissingBean sees yours and skips its own, so your configuration wins.

A JsonConfig class that defines its own JsonMapper, and the output that shows Boot's bean stepped aside.

Example 2 · src/main/java/com/shoplite/lab/JsonConfig.java

Runs in: the boot-lab practice project (Spring Boot 4.1)

JsonConfig.javaJava
// src/main/java/com/shoplite/lab/JsonConfig.javapackage com.shoplite.lab;
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
import tools.jackson.databind.SerializationFeature;import tools.jackson.databind.json.JsonMapper;
@Configurationpublic class JsonConfig {
    @Bean    public JsonMapper shopJsonMapper(JsonMapper.Builder builder) {        return builder.enable(SerializationFeature.INDENT_OUTPUT).build();    }}
Output
JsonMapper beans: [shopJsonMapper]
{
  "name" : "A4 notebook",
  "price" : 45.50,
  "addedOn" : "2026-07-01"
}

What this code does

  • Our @Bean method defines a JsonMapper. Boot's jacksonJsonMapper has @ConditionalOnMissingBean, so it is not created: the context now holds only shopJsonMapper, and the runner from Example 1 receives ours.
  • The method asks for JsonMapper.Builder, a bean Boot still provides with all of its settings applied. Building from it keeps Boot's defaults and adds one change, INDENT_OUTPUT, which prints the JSON over several lines.
  • Delete JsonConfig.java and run again: Boot's mapper comes back. Backing off works both ways.

Backing off is how you customise Boot without fighting it. Need a different JSON setup, a different connection pool or a different clock? Define the bean, and Boot steps aside for that one bean while keeping everything else.

Two cautions. First, when you replace a bean you also lose the settings Boot would have applied to it, unless you build yours from the builder Boot provides (Example 2 does). Second, check whether a property already does the job (spring.jackson.serialization.indent-output=true would do the same as Example 2); a property is less code to maintain.

Order of execution

How Boot decides about one bean

Put the steps in the order Boot takes them for the JSON mapper.

The conditions report with --debug, and excluding an auto-configuration

The conditions report is the list Spring Boot prints when you start with --debug. It shows every auto-configuration with the reason it matched (positive matches) or did not (negative matches).

Two ways to start boot-lab with the report switched on.

Terminal
./mvnw spring-boot:run -Dspring-boot.run.arguments=--debugjava -jar target/boot-lab-0.0.1-SNAPSHOT.jar --debug

Example 3 · The conditions report for Example 2

Runs in: the boot-lab practice project (Spring Boot 4.1)

Terminal
java -jar target/boot-lab-0.0.1-SNAPSHOT.jar --debug
Sample output (trimmed with ...)
...
============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:
-----------------
...
   JacksonAutoConfiguration matched:
      - @ConditionalOnClass found required class 'tools.jackson.databind.json.JsonMapper' (OnClassCondition)
...
   JacksonAutoConfiguration#jsonMapperBuilder matched:
      - @ConditionalOnMissingBean (types: tools.jackson.databind.json.JsonMapper$Builder; SearchStrategy: all) did not find any beans (OnBeanCondition)
...

Negative matches:
-----------------
...
   JacksonAutoConfiguration#jacksonJsonMapper:
      Did not match:
         - @ConditionalOnMissingBean (types: tools.jackson.databind.json.JsonMapper; SearchStrategy: all) found beans of type 'tools.jackson.databind.json.JsonMapper' shopJsonMapper (OnBeanCondition)

   JacksonAutoConfiguration.CborConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'tools.jackson.dataformat.cbor.CBORMapper' (OnClassCondition)
...

Exclusions:
-----------

    None
...

What this code does

  • Positive matches are configurations whose conditions passed. Jackson's auto-configuration matched because the class JsonMapper is on the class path.
  • Negative matches explain every bean Boot did not create. jacksonJsonMapper was skipped because our shopJsonMapper exists; the CBOR (binary JSON) setup was skipped because its library is missing.
  • The real report is a few hundred lines. Search it (Ctrl+F in the IDE console) for the class or bean name you care about.

The report prints after startup, under CONDITIONS EVALUATION REPORT; debug=true in application.properties does the same. Use it when Boot created a bean you did not expect, or did not create one you need. Find the name, read the condition: "did not find required class" means a missing dependency; "found beans of type" means your bean replaced Boot's.

To switch an auto-configuration off completely, exclude it: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class), or the property spring.autoconfigure.exclude with the class's full name. Excluded classes appear under Exclusions in the report.

On Windows PowerShell write .\mvnw, and wrap the -D... argument in double quotes.

'Failed to configure a DataSource: url attribute is not specified'

Three runs: the JDBC starter with no database URL, the same app with the settings, and the exclusion instead.

Example 4 · Adding the JDBC starter without database settings

Runs in: the boot-lab practice project (Spring Boot 4.1)

XML
<!-- pom.xml, inside <dependencies> --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency>    <groupId>com.mysql</groupId>    <artifactId>mysql-connector-j</artifactId>    <scope>runtime</scope></dependency>
Sample output (trimmed with ...)
> java -jar target/boot-lab-0.0.1-SNAPSHOT.jar
...
2026-10-16T10:22:01.485+05:30  INFO 3264 --- [boot-lab] [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat initialized with port 8080 (http)
...
2026-10-16T10:22:04.576+05:30  WARN 3264 --- [boot-lab] [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/jdbc/autoconfigure/DataSourceConfiguration$Hikari.class]: ...
2026-10-16T10:22:04.581+05:30  INFO 3264 --- [boot-lab] [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
...
2026-10-16T10:22:04.677+05:30 ERROR 3264 --- [boot-lab] [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

What this code does

  • DataSourceAutoConfiguration matched (the JDBC classes are now on the class path) and tried to build a connection pool. With no spring.datasource.url and no in-memory database such as H2, it cannot know where to connect, so the app stops.
  • "Failed to determine a suitable driver class" is the same problem seen from the driver side: Boot picks the driver from the URL, and there is no URL.
  • The Action lists two cases that do not fit ShopLite (an embedded database, a profile). The real fix for a MySQL app is to give it the URL, as Example 5 does.

Example 5 · application.properties, DatabaseCheck.java

Runs in: the boot-lab practice project with the ShopLite MySQL database

DatabaseCheck.javaJava
# src/main/resources/application.propertiesspring.application.name=boot-labspring.datasource.url=${DB_URL}spring.datasource.username=${DB_USER}spring.datasource.password=${DB_PASSWORD}
// src/main/java/com/shoplite/lab/DatabaseCheck.javapackage com.shoplite.lab;
import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class DatabaseCheck implements CommandLineRunner {
    private final DataSource dataSource;
    public DatabaseCheck(DataSource dataSource) {   // the DataSource bean Boot built        this.dataSource = dataSource;    }
    @Override    public void run(String... args) throws SQLException {        try (Connection con = dataSource.getConnection();             Statement st = con.createStatement();             ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM products")) {            rs.next();            System.out.println("DataSource type: " + dataSource.getClass().getSimpleName());            System.out.println("Products in the database: " + rs.getInt(1));        }    }}
Sample output (trimmed with ...)
...
2026-10-16T10:26:06.155+05:30  INFO 23712 --- [boot-lab] [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'
2026-10-16T10:26:06.187+05:30  INFO 23712 --- [boot-lab] [           main] com.shoplite.lab.BootLabApplication      : Started BootLabApplication in 5.966 seconds (process running for 7.367)
2026-10-16T10:26:06.193+05:30  INFO 23712 --- [boot-lab] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2026-10-16T10:26:07.007+05:30  INFO 23712 --- [boot-lab] [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@76a7fcbd
2026-10-16T10:26:07.012+05:30  INFO 23712 --- [boot-lab] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
DataSource type: HikariDataSource
Products in the database: 15

What this code does

  • ${DB_URL} reads an environment variable, so no password is written in the project. Set DB_URL=jdbc:mysql://localhost:3306/shoplite, DB_USER and DB_PASSWORD in the terminal or in the IDE run configuration before starting.
  • Boot built a HikariDataSource (a connection pool) from the three properties. The pool opens its first connection when DatabaseCheck asks for one, which is why the Hikari lines come after "Started".
  • Remove the two quiet lines (banner-mode, logging.level.root) from the properties before this run, or the Hikari lines are hidden. The count is 15 on the Section 12 ShopLite seed data.

Example 6 · Excluding DataSourceAutoConfiguration instead

Runs in: the boot-lab practice project (Spring Boot 4.1)

BootLabApplication.javaJava
// src/main/java/com/shoplite/lab/BootLabApplication.javapackage com.shoplite.lab;
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)public class BootLabApplication {
    public static void main(String[] args) {        SpringApplication.run(BootLabApplication.class, args);    }}
Sample output (trimmed with ...)
> java -jar target/boot-lab-0.0.1-SNAPSHOT.jar --debug
...
   JdbcTemplateAutoConfiguration:
      Did not match:
         - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans (OnBeanCondition)
...
Exclusions:
-----------

    org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration
...
2026-10-16T10:28:47.068+05:30  INFO 24144 --- [boot-lab] [           main] com.shoplite.lab.BootLabApplication      : Started BootLabApplication in 10.387 seconds (process running for 11.91)

What this code does

  • With exclude, Boot never even evaluates DataSourceAutoConfiguration, and the report lists it under Exclusions. The app starts with no database settings (and no DatabaseCheck, which would need a DataSource).
  • Everything that needs a DataSource backs off too: JdbcTemplateAutoConfiguration did not match because no DataSource bean exists.
  • In Boot 4 the class lives in org.springframework.boot.jdbc.autoconfigure; Boot 2 and 3 tutorials import it from org.springframework.boot.autoconfigure.jdbc, which no longer compiles.

Failed to configure a DataSource means the JDBC starter is on the class path, so Boot tries to build a connection pool, but no spring.datasource.url tells it which database to use. It is the most common first startup failure in Spring Boot.

The cause is never in your Java code: it is a starter plus missing settings. Want a database? Set spring.datasource.url, username and password (ShopLite reads them from environment variables). Not using a database yet? Remove the JDBC starter, or exclude DataSourceAutoConfiguration. Watch for the trap in the Action text: adding H2 makes the error go away, but your app then talks to an empty in-memory database instead of MySQL.

Never put a real password in application.properties. It ends up in Git, and Git history keeps it even after you delete the line.

Next step

Check your understanding

11 quick questions