skip to content

SpringApplication & builder

SpringApplication.run detects the application type, prepares the environment, refreshes the context and starts the server, and the builder lets you tune all of that first. Being able to list those stages is the answer to 'what happens when you run main'.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

5

What does SpringApplication.run(...) do when a Spring Boot application starts?

level: juniorimportance: must knowfreq 78%

answer

  1. one line in main() bootstraps everything
  2. primary source = @SpringBootApplication class
  3. infer type -> Environment -> context -> refresh
  4. refresh starts embedded server
  5. returns ConfigurableApplicationContext

basics

~10 s

SpringApplication.run() bootstraps the app: it creates and configures the Spring ApplicationContext, runs auto-configuration, starts any embedded web server, and returns the running context. It's the one line called from main().

solid answer

~40 s

SpringApplication.run(MyApp.class, args) is the entry point Spring Boot's main() calls. It creates a SpringApplication for the given primary source (usually your @SpringBootApplication class), then bootstraps the whole app: it decides the application type (servlet/reactive/none), creates the matching ApplicationContext, prepares the Environment (loading application.properties/yaml, profiles, command-line args), prints the banner, applies ApplicationContextInitializers, registers bean definitions, and finally refreshes the context. Refresh instantiates singletons, runs auto-configuration, and starts an embedded web server (Tomcat by default) if it's a web app. It fires lifecycle events throughout (ApplicationStartingEvent, EnvironmentPreparedEvent, ContextRefreshedEvent, ApplicationReadyEvent) and calls any ApplicationRunner/CommandLineRunner beans. It returns the ConfigurableApplicationContext so you can inspect beans if needed.

code

java · 9 lines
java
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx =
            SpringApplication.run(DemoApplication.class, args);
        // ctx is the running context; usually you don't need to touch it
        System.out.println("Beans loaded: " + ctx.getBeanDefinitionCount());
    }
}

go deeper

for a junior

Should know it bootstraps the ApplicationContext and starts the embedded server, called from main().

for a middle

Should describe Environment prep, refresh, and the lifecycle events fired.

for a senior

Should articulate the ordered phases and where auto-config and server start happen.

for a principal

Should connect run() phases to extension points (initializers, listeners, spring.factories) and startup performance.

## What it is `SpringApplication` is Spring Boot's bootstrap class. The static `SpringApplication.run(Class<?> primarySource, String... args)` is a convenience that does `new SpringApplication(primarySource).run(args)`. It is the single call your `public static void main` uses to launch the whole application. ## The primary source The class you pass (typically the one annotated with `@SpringBootApplication`) is the **primary source** of bean definitions. `@SpringBootApplication` is itself a meta-annotation combining `@SpringBootConfiguration` (a `@Configuration`), `@EnableAutoConfiguration` (turns on Boot's auto-configuration), and `@ComponentScan` (scans the package of that class and below). So passing that one class tells Boot where to scan and to enable auto-config. ## What run() does, step by step 1. **Create the `SpringApplication`** and infer the **web application type** by inspecting the classpath (SERVLET, REACTIVE, or NONE). 2. **Fire `ApplicationStartingEvent`** via registered `ApplicationListener`s and `SpringApplicationRunListener`s (discovered from `META-INF/spring.factories` / `spring/…imports`). 3. **Prepare the `Environment`**: bind command-line `args`, system properties, OS env vars, and load `application.properties`/`application.yml`, activate profiles. Fires `ApplicationEnvironmentPreparedEvent`. 4. **Print the banner** (`Banner.Mode`). 5. **Create the `ApplicationContext`** matching the web type (`AnnotationConfigServletWebServerApplicationContext`, `AnnotationConfigReactiveWebServerApplicationContext`, or `AnnotationConfigApplicationContext`). 6. **Prepare the context**: apply `ApplicationContextInitializer`s, register the primary sources as bean definitions, fire `ApplicationContextInitializedEvent` and `ApplicationPreparedEvent`. 7. **Refresh the context** (`AbstractApplicationContext.refresh()`): this is the heavy part — process `@Configuration`, run all auto-configuration, instantiate singleton beans, and **start the embedded web server** for a web app. Fires `ContextRefreshedEvent`. 8. **Call runners**: every `ApplicationRunner` and `CommandLineRunner` bean is invoked. 9. **Fire `ApplicationReadyEvent`** — the app is fully up. If anything throws, `ApplicationFailedEvent` fires and the exception propagates. ## Return value `run` returns a `ConfigurableApplicationContext`. Most apps ignore it, but you can capture it to look up beans programmatically, e.g. in tests or CLI tools. ## Gotchas - The embedded server starts **during refresh**, not after — so a `ContextRefreshedEvent` listener already sees the server listening. - `SpringApplication.run` blocks only in the sense that startup is synchronous; the JVM stays alive because a web app has non-daemon server threads. A `NONE` (non-web) app will exit after `run` returns unless something keeps it alive. - Passing the wrong class (one without component scanning) means no beans get found.

  • What is the 'primary source' you pass to run()?
    The bean-definition source Boot uses to start scanning and configuring — normally the @SpringBootApplication class, which enables component scanning and auto-configuration from its package.
  • At what point does the embedded Tomcat start?
    During context refresh (step inside AbstractApplicationContext.refresh), not as a separate step after run() — a WebServerApplicationContext starts the server as part of refreshing.

saying these in an interview costs you the question

  • Saying run() only 'starts Tomcat' and ignoring context creation/refresh
  • Claiming the embedded server starts after run() returns
  • Thinking you must pass every @Configuration class, not just the primary source

context

open as a page

How does Spring Boot decide whether an app is SERVLET, REACTIVE, or NONE, and how do you override it?

level: middleimportance: must knowfreq 62%

basics

~20 s

Boot inspects the classpath. If Spring MVC (servlet) classes are present it picks SERVLET; if only WebFlux is present it picks REACTIVE; if no web classes are present it picks NONE. Override with setWebApplicationType() or spring.main.web-application-type.

open as a page

What are 'primary sources' passed to SpringApplication, and how do they differ from component scanning?

level: middleimportance: should knowfreq 40%

basics

~20 s

Primary sources are the classes (or bean-definition sources) you hand to SpringApplication to seed the context — usually your one @SpringBootApplication class. Component scanning then discovers the rest of your beans from that class's package downward.

open as a page

What is SpringApplicationBuilder and when would you use its parent/child context feature?

level: seniorimportance: should knowfreq 34%

basics

~10 s

SpringApplicationBuilder is a fluent API for configuring and launching a SpringApplication. Its distinctive feature is building a parent/child ApplicationContext hierarchy — a shared parent context whose beans are visible to isolated child contexts.

open as a page

What can you customize on a SpringApplication BEFORE the context refreshes, and how do you hook in?

level: principalimportance: should knowfreq 30%

basics

~20 s

Before refresh you can set defaults on the SpringApplication instance: default properties, additional profiles, banner mode, web type, lazy initialization, and register ApplicationContextInitializers and ApplicationListeners. These run during the early bootstrap phases, before beans are instantiated.

open as a page