Cheatsheet

Spring Boot: starters and startup

Key idea

Spring Boot is opinionated Spring: *starters* bring coherent dependencies, auto-configuration creates the usual beans based on what's on the classpath and `SpringApplication.run` starts the context and the embedded server from a `main`. The result is packaged as an executable jar.

Diagram (UML)

ApplicationContextstarters (pom.xml)java -jar box.jarSpringApplication@SpringBootApplicationauto-configurationembedded TomcatCommandLine/ApplicationRunnerApplicationReadyEvent

Key pieces

  • @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
  • SpringApplication.run(App.class, args) → ConfigurableApplicationContext
  • SpringApplicationBuilder, setWebApplicationType(...), spring.main.*
  • Starters: spring-boot-starter-webmvc, -data-jpa, -security, -actuator, -test…
  • spring-boot-starter-parent (or the spring-boot-dependencies BOM) and spring-boot-maven-plugin
  • CommandLineRunner, ApplicationRunner, ApplicationReadyEvent

BoxApplication.java

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

    public static void main(String[] args) {
        SpringApplication.run(BoxApplication.class, args); // creates the context, starts Tomcat, runs runners
    }
}

Remember for the exam

  • @SpringBootConfiguration is a @Configuration; that's why the main class can declare @Beans
  • @ComponentScan starts at the main class's package: put it in the root package
  • SpringApplication picks the context type from the classpath: servlet (Spring MVC), reactive (WebFlux) or none
  • A starter is a code-less dependency grouping others; the parent/BOM pins their versions, so you write no <version>
  • Runners run once the context is ready, before ApplicationReadyEvent; their order is set with @Order
  • CommandLineRunner gets String... args; ApplicationRunner, already-parsed ApplicationArguments (--box=norte)
  • spring-boot-maven-plugin repackages an executable jar (fat jar) with the dependencies in BOOT-INF/lib: java -jar app.jar

Exam traps

  • If the main class is in a subpackage, components in sibling packages are not scanned
  • Spring Boot isn't a different framework: it's still Spring (same container, same annotations)
  • Adding @EnableWebMvc to your configuration turns off Boot's Spring MVC auto-configuration
  • To deploy as a WAR to an external server you need to extend SpringBootServletInitializer

← Spring Boot: starters and startup · Run it