Auto-configuration

Spring Boot · lesson 3 of 39 · 3 min read

Explain how Boot configures beans from what is on the classpath, and how to override them.

Open this lesson in the learning hub

Key points

  • @SpringBootApplication is three annotations in one: config, component scan, and auto-configuration.
  • Auto-config asks questions about the classpath: Is Tomcat present? Then start a web server.
  • The rules live in conditions like @ConditionalOnClass and @ConditionalOnMissingBean.
  • @ConditionalOnMissingBean is the escape hatch — define your own bean and Boot backs off.
  • Component scan starts at the package of your main class. Keep it at the root of your code.
  • Run with --debug to print the report of which auto-configurations matched and why.

Example

package com.example.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
@SpringBootApplication
public class ShopApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

// Anything in com.example.shop.** is scanned automatically.
// Classes in a sibling package like com.other are NOT.

Auto-configuration is a pile of "if you have X and did not define Y" rules — and you always win.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Boot course, and every lesson in it is listed on the Spring Boot contents page.