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)
sequenceDiagram actor D as java -jar box.jar participant L as JarLauncher participant S as SpringApplication participant E as Environment participant C as ApplicationContext participant T as Embedded Tomcat participant R as Runners D->>L: Main-Class L->>S: BoxApplication.main(args) → run() S->>E: properties, profiles, --args S->>C: create (servlet / reactive / none, from the classpath) S->>C: refresh: @ComponentScan + @EnableAutoConfiguration + beans C->>T: start web server S-->>S: ApplicationStartedEvent S->>R: CommandLineRunner / ApplicationRunner (@Order) S-->>S: ApplicationReadyEvent S-->>D: ConfigurableApplicationContext
Key pieces
@SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScanSpringApplication.run(App.class, args)→ConfigurableApplicationContextSpringApplicationBuilder,setWebApplicationType(...),spring.main.*- Starters:
spring-boot-starter-webmvc,-data-jpa,-security,-actuator,-test… spring-boot-starter-parent(or thespring-boot-dependenciesBOM) andspring-boot-maven-pluginCommandLineRunner,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
@SpringBootConfigurationis a@Configuration; that's why the main class can declare@Beans@ComponentScanstarts at the main class's package: put it in the root packageSpringApplicationpicks 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 CommandLineRunnergetsString... args;ApplicationRunner, already-parsedApplicationArguments(--box=norte)spring-boot-maven-pluginrepackages an executable jar (fat jar) with the dependencies inBOOT-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
@EnableWebMvcto your configuration turns off Boot's Spring MVC auto-configuration - To deploy as a WAR to an external server you need to extend
SpringBootServletInitializer