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.
In the box
Starting the box app by hand meant creating the context, Tomcat and the DispatcherServlet in main. See what Spring Boot does for you, with @SpringBootApplication, SpringApplication.run, starters, runners, startup events and the executable jar.
java -jar box.jarManualBootstrap

The java -jar command calls ManualBootstrap, highlighted in red, which creates Tomcat and the DispatcherServlet by hand.

SpringApplication receives the class annotated with @SpringBootApplication, highlighted, as the primary configuration source.

The command calls run(args) on SpringApplication; auto-configuration kicks in and starts the embedded Tomcat. SpringApplication and Tomcat are highlighted.

The pom's starters, outside the context and highlighted, put the jars on the classpath; auto-configuration sees them and acts.

SpringApplication calls run(args) on the runners, highlighted, once the context is ready.

SpringApplication publishes ApplicationReadyEvent, highlighted, after running the runners.

The command asks SpringApplication, highlighted, for web(NONE): the application starts without Tomcat.

java -jar box.jar, highlighted, starts the JarLauncher, which calls main, which calls SpringApplication.

Final view: the command, SpringApplication, the main class, auto-configuration and Tomcat in a row; the starters above and the runners and the ready event below.

Step 1 of 9

Building everything in main

Before Spring Boot, starting the box's web app was plumbing work in main:

  1. Create an AnnotationConfigWebApplicationContext and register the configuration, with @EnableWebMvc, Jackson, DataSource, transactions… all declared by hand.
  2. Create a Tomcat, set the port and the connector.
  3. Register the DispatcherServlet and map it to /.
  4. Start and wait.

And on top of that, pick and align the versions of dozens of dependencies by hand.

Step 2 of 9

@SpringBootApplication

With Spring Boot, the main class carries an annotation that is the sum of three:

  • @SpringBootConfiguration: it's a @Configuration (you can declare @Beans in it) and marks the class @SpringBootTest will look for.
  • @EnableAutoConfiguration: turns on auto-configuration (next lesson).
  • @ComponentScan: scans from this class's package downwards.

The test checks it with AnnotatedElementUtils: the class has all three (and @Configuration, through @SpringBootConfiguration).

Step 3 of 9

SpringApplication.run

SpringApplication.run(BoxApplication.class, args) does the whole startup:

  1. Prepares the Environment (properties, profiles, arguments).
  2. Picks the context type from the classpath: with Spring MVC, a servlet web one; with WebFlux, a reactive one; with nothing web, a plain one.
  3. Creates and refreshes the context: scanning, auto-configuration and beans. If it's web, it starts the embedded server.
  4. Runs the runners and publishes ApplicationReadyEvent.
  5. Returns the ConfigurableApplicationContext.

The test starts the app with server.port=0 (a free port) and checks the context is a WebServerApplicationContext with a real port.

Step 4 of 9

Starters and the parent

Where do Tomcat, Jackson or Hibernate come from? From the starters: code-less dependencies grouping everything a feature needs.

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>4.0.9</version>
</parent>
<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId> <!-- no <version> -->
  </dependency>
</dependencies>
  • spring-boot-starter-webmvc brings Spring MVC, Jackson and embedded Tomcat; -data-jpa, Hibernate and Spring Data; -security, -actuator, -test…
  • The parent (or importing the spring-boot-dependencies BOM) pins compatible versions of everything: that's why you write no <version>. It also configures the compiler, resources and Boot's plugin.

Step 5 of 9

Code at startup: runners

To do something at startup (load data, check something, launch a process), declare a bean of type:

  • CommandLineRunner: gets the arguments as they are, String... args.
  • ApplicationRunner: gets already-parsed ApplicationArguments: args.getOptionValues("box") for --box=norte.

They run once the context is ready (every bean created, server started), inside run(), in @Order order. The test checks it: seed: 2 args and then open: box=[norte].

Step 6 of 9

Startup events

During startup, SpringApplication publishes events. The most useful ones:

  • ApplicationStartedEvent: context refreshed, before the runners.
  • ApplicationReadyEvent: after the runners. The application is ready for traffic.
  • ApplicationFailedEvent: startup failed.

StartupHooks listens for ApplicationReadyEvent with @EventListener and records ready, which appears in the log after both runners.

Step 7 of 9

Customizing startup

SpringApplication can be tuned before starting, with SpringApplicationBuilder or with spring.main.* properties:

  • .web(WebApplicationType.NONE): no server even with Spring MVC on the classpath (handy for batch jobs or tools).
  • .properties(...), .profiles(...), banner (spring.main.banner-mode=off), lazy startup (spring.main.lazy-initialization)…

The second test starts the same application without a server: the context is not a WebServerApplicationContext.

Step 8 of 9

The executable jar

spring-boot-maven-plugin (goal repackage) turns the plain jar into an executable jar (fat jar):

box.jar
├── META-INF/MANIFEST.MF     Main-Class: org.springframework.boot.loader.launch.JarLauncher
├── BOOT-INF/classes/        your classes and resources
└── BOOT-INF/lib/            every dependency, as nested jars

java -jar box.jar starts Spring Boot's JarLauncher, which builds a classpath from the nested jars and calls your main. No application server needed: Tomcat is inside.

Step 9 of 9

Recap

  • @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan (from the root package).
  • SpringApplication.run: environment → context type → refresh (and server) → runners → ApplicationReadyEvent.
  • Starters + parent/BOM: coherent dependencies, no versions.
  • CommandLineRunner/ApplicationRunner with @Order; startup events.
  • Fat jar with spring-boot-maven-plugin: java -jar.

Cheatsheet →

Code

ManualBootstrap.java

/** Before: wiring the context, the servlet container and the DispatcherServlet by hand. */
public class ManualBootstrap {

    @EnableWebMvc                    // + Jackson, DataSource, transactions… all declared by hand
    static class WebConfig {         // (registered explicitly below, so it isn't a scanned @Configuration)
    }

    public static void main(String[] args) throws Exception {
        var spring = new AnnotationConfigWebApplicationContext();
        spring.register(WebConfig.class);

        Tomcat tomcat = new Tomcat();                       // the server, by hand
        tomcat.setPort(8080);
        tomcat.getConnector();
        Context web = tomcat.addContext("", null);
        Tomcat.addServlet(web, "dispatcher", new DispatcherServlet(spring)); // the front controller, by hand
        web.addServletMappingDecoded("/", "dispatcher");
        tomcat.start();
        tomcat.getServer().await();
    }
}

SpringBootApplicationTest.java

@Test
void springBootApplicationIsThreeAnnotationsInOne() {
    assertThat(AnnotatedElementUtils.hasAnnotation(BoxApplication.class, SpringBootConfiguration.class)).isTrue();
    assertThat(AnnotatedElementUtils.hasAnnotation(BoxApplication.class, Configuration.class)).isTrue(); // via @SpringBootConfiguration
    assertThat(AnnotatedElementUtils.hasAnnotation(BoxApplication.class, EnableAutoConfiguration.class)).isTrue();
    assertThat(AnnotatedElementUtils.hasAnnotation(BoxApplication.class, ComponentScan.class)).isTrue();
}

SpringApplicationTest.java

@Test
void runStartsTheServerAndTheRunnersAndReturnsTheContext() {
    try (ConfigurableApplicationContext ctx = new SpringApplicationBuilder(BoxApplication.class)
            .properties("server.port=0")                       // any free port
            .run("--box=norte", "extra")) {
        assertThat(ctx).isInstanceOf(WebServerApplicationContext.class); // webmvc on the classpath → servlet app
        assertThat(((WebServerApplicationContext) ctx).getWebServer().getPort()).isPositive();
        assertThat(ctx.getBean(StartupLog.class).lines())
            .containsExactly("seed: 2 args", "open: box=[norte]", "ready"); // runners in @Order, then ready
    }
}

No code in this step.

StartupHooks.java

@Bean
@Order(1)
CommandLineRunner seedClasses(StartupLog log) {             // raw String... args
    return args -> log.add("seed: " + args.length + " args");
}

@Bean
@Order(2)
ApplicationRunner openBox(StartupLog log) {                 // parsed arguments
    return args -> log.add("open: box=" + args.getOptionValues("box"));
}

StartupHooks.java

@EventListener(ApplicationReadyEvent.class)                 // after the runners: ready for traffic
void ready(ApplicationReadyEvent event) {
    event.getApplicationContext().getBean(StartupLog.class).add("ready");
}

SpringApplicationTest.java

@Test
void theApplicationTypeCanBeForced() {
    try (var ctx = new SpringApplicationBuilder(BoxApplication.class)
            .web(WebApplicationType.NONE)        // no server: a plain ApplicationContext
            .properties("spring.main.banner-mode=off")
            .run()) {
        assertThat(ctx).isNotInstanceOf(WebServerApplicationContext.class);
        assertThat(ctx.getBean(StartupLog.class).lines()).contains("ready");
    }
}

No code in this step.

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
    }
}

Quiz

1. Which three annotations does @SpringBootApplication combine?

2. What is a Spring Boot starter?

3. When does a CommandLineRunner bean run?

4. The @SpringBootApplication class lives in com.box.app and a @Service lives in com.box.billing. What happens?

5. What does spring-boot-maven-plugin produce when packaging?

6. With spring-boot-starter-webmvc on the classpath, how do you start the application without a web server (for instance, for a batch job)?

Cheatsheet → · Mock exam →

Run it