Easy java spring

What does @SpringBootApplication do?

The 30 second answer

It is a shortcut for three annotations. @SpringBootConfiguration marks the class as a configuration source, @EnableAutoConfiguration turns on Spring Boot's auto-configuration, and @ComponentScan scans the class's package and sub-packages for components. That is why the main class should sit in the root package: classes outside it are not picked up.

<!-- level: 1 --> <!-- must_know: true -->

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

The Spring Boot reference says a single @SpringBootApplication enables three features:

  • @EnableAutoConfiguration: turns on Spring Boot's auto-configuration.
  • @ComponentScan: scans for @Component classes in the package where the application is located.
  • @SpringBootConfiguration: lets you register extra beans or import more configuration classes in the context (a specialised @Configuration).

SpringApplication.run creates the application context, runs auto-configuration, creates the beans, starts the embedded web server if it is a web app, and then runs any CommandLineRunner or ApplicationRunner beans.

Common follow-up: "A @Service is not found." The usual reason is that it lives in a package that is not under the main class's package, so component scanning never sees it.

Sources (1)
  1. Spring Boot reference: Using the @SpringBootApplication annotationdocs.spring.io