Spring Boot Application Startup Process
The Spring Boot application startup process is everything that happens between typing java -jar order-service.jar and the log line that says the application has started. In those one or two seconds, Spring Boot reads your configuration, creates the application context, builds every bean, starts the embedded web server and finally tells the world it is ready for traffic. Knowing these steps helps you put code in the right place, read startup logs with confidence and fix failures quickly.
This tutorial walks through SpringApplication.run() one step at a time, lists the startup events in the order they fire, and builds a small order service that prints each phase. It also covers how to customize startup, how to measure and speed it up, and how to fix the most common startup errors.
1. What Is the Spring Boot Application Startup Process?
Every Spring Boot application has a main method that calls SpringApplication.run(). That single call is the startup process. It turns a plain Java program into a running Spring application by doing four big jobs:
- Prepare the environment: collect configuration from properties files, environment variables, command-line arguments and active profiles.
- Create the application context: the application context is Spring's container. It holds every object Spring manages, called a bean.
- Refresh the context: find your classes, apply auto-configuration, create the beans and connect them together. For a web application this step also starts the embedded server, such as Tomcat.
- Signal readiness: run your startup tasks and publish events that say the application is live and ready to accept requests.
2. Why the Startup Sequence Matters
You can write many Spring Boot applications without thinking about startup. But sooner or later you need to know it:
| Situation | What the startup sequence tells you |
|---|---|
| You want to warm a cache or load reference data once | Use a runner or an ApplicationReadyEvent listener, not a constructor |
| A listener for an early event never runs | Early events fire before beans exist, so the listener must be registered differently |
| The application fails with "APPLICATION FAILED TO START" | Which phase failed, and therefore where to look |
| Kubernetes kills the pod during a slow start | Which phase is slow, and when readiness is actually reported |
| You need a value before beans are created | Hook into environment preparation instead of reading it in a bean |
3. The Startup Sequence at a Glance
The diagram shows the main phases in order. The highlighted phase, the context refresh, is where most of the time goes, because it creates all your beans and starts the web server.
4. Inside SpringApplication.run(), Step by Step
Here is the typical entry point. Everything in this section happens inside the one line in main.
package com.javabytechie.shop.order;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
4.1 Creating the SpringApplication Object
The static run() method first creates a SpringApplication object. Its constructor does three things before any configuration is read:
- Detects the application type. It checks the classpath. If Spring MVC and a servlet container are present, the type is
SERVLET. If only Spring WebFlux is present, it isREACTIVE. Otherwise it isNONE, a plain non-web application. - Loads early extensions. It reads
META-INF/spring.factoriesfiles from all JARs to findBootstrapRegistryInitializer,ApplicationContextInitializerandApplicationListenerimplementations. These must exist before any bean does. - Finds the main class. It records which class contains
main, so it can log it and use it later.
4.2 Starting the Run Listeners
When run() starts, Spring Boot records the start time, creates a small bootstrap context (a temporary holder for objects that are expensive to create and needed before the real context exists), and creates the run listeners. A run listener turns each phase into an event. The first one, ApplicationStartingEvent, is published right away.
4.3 Preparing the Environment
The environment (ConfigurableEnvironment) is the object that answers "what is the value of this property?" and "which profiles are active?". Spring Boot builds it from several property sources: command-line arguments, Java system properties, operating system environment variables and the application.properties or application.yml files, including profile-specific ones. Each source has a priority, so a command-line argument wins over the same key in a file.
When the environment is ready, Spring Boot publishes ApplicationEnvironmentPreparedEvent. Classes that implement EnvironmentPostProcessor run at this point and can add or change property sources. Loading of the configuration files themselves is done by one of these post-processors.
4.4 Printing the Banner
Next comes the familiar ASCII banner. You can replace it with a banner.txt file in src/main/resources or switch it off with spring.main.banner-mode=off.
4.5 Creating the Application Context
Spring Boot now creates an empty application context that matches the application type. For a servlet web application it is an AnnotationConfigServletWebServerApplicationContext, a context that knows how to create an embedded web server. For a reactive application it is the reactive equivalent, and for NONE it is a plain AnnotationConfigApplicationContext.
4.6 Preparing the Context
The context gets the environment, and all ApplicationContextInitializer objects run. Then ApplicationContextInitializedEvent is published, the bootstrap context is closed, and Spring Boot logs the "Starting ..." line with the Java version and process ID. Finally your main class is registered as the first bean definition (a recipe that says how to create a bean), and ApplicationPreparedEvent is published. No beans of yours exist yet.
4.7 Refreshing the Context
Refresh is the heart of startup. It is the Spring Framework's refresh() method, and it runs in a fixed order:
- Read the configuration classes. Starting from your main class, Spring processes
@SpringBootApplication. Component scanning finds your@Component,@Service,@Repositoryand@Controllerclasses, and the auto-configuration import adds Spring Boot's configuration classes for the libraries on your classpath. Their conditions, such as@ConditionalOnMissingBean, are evaluated here. - Run bean factory post-processors. These can change bean definitions before any bean is created, for example to resolve
${...}placeholders. - Register bean post-processors. These wrap or modify beans as they are created, for example to add
@Transactionalproxies. - Create the web server. A web context creates the embedded Tomcat (or Jetty) here. The port is configured, but the server does not accept requests yet.
- Create all singleton beans. Every non-lazy singleton is instantiated, its dependencies are injected, and its
@PostConstructmethod runs. This is usually the slowest part. - Finish the refresh. Lifecycle beans start. This is when the web server starts listening and
WebServerInitializedEventis published. Then the context publishesContextRefreshedEvent.
After the refresh, Spring Boot registers a shutdown hook (so the context closes cleanly when the JVM stops), logs "Started ... in X seconds", and publishes ApplicationStartedEvent, followed by an AvailabilityChangeEvent with LivenessState.CORRECT.
4.8 Calling the Runners
Spring Boot then calls every bean that implements ApplicationRunner or CommandLineRunner, ordered by @Order if present. Both receive the command-line arguments: ApplicationRunner gets them parsed as ApplicationArguments, CommandLineRunner gets the raw String[]. If a runner throws an exception, startup fails.
4.9 Announcing That the Application Is Ready
Last, Spring Boot publishes ApplicationReadyEvent and then an AvailabilityChangeEvent with ReadinessState.ACCEPTING_TRAFFIC. If you use Actuator health groups on Kubernetes, the readiness probe reports "UP" from this moment. The run() method returns the context, and the main thread ends while the web server's threads keep the JVM running.
5. Spring Boot Startup Events in Order
Each phase publishes an event you can listen to. This table lists them in the order they are published during a successful start of a web application:
| # | Event | Published when | Can a @Component listener receive it? |
|---|---|---|---|
| 1 | ApplicationStartingEvent | At the very start of run() | No |
| 2 | ApplicationEnvironmentPreparedEvent | Environment is ready, context not created | No |
| 3 | ApplicationContextInitializedEvent | Context created and initializers applied, no bean definitions loaded | No |
| 4 | ApplicationPreparedEvent | Bean definitions loaded, refresh about to start | No |
| 5 | WebServerInitializedEvent | Embedded web server is started (web apps only) | Yes |
| 6 | ContextRefreshedEvent | Refresh finished, all singletons created | Yes |
| 7 | ApplicationStartedEvent | After refresh, before runners | Yes |
| 8 | AvailabilityChangeEvent (LivenessState.CORRECT) | Right after ApplicationStartedEvent | Yes |
| 9 | ApplicationReadyEvent | After all runners have finished | Yes |
| 10 | AvailabilityChangeEvent (ReadinessState.ACCEPTING_TRAFFIC) | Right after ApplicationReadyEvent | Yes |
If startup fails at any point, ApplicationFailedEvent is published instead of the remaining events.
@Component listener is itself a bean, and beans are created during the refresh. Events 1 to 4 fire before that, so nobody is there to hear them. Register listeners for those events with SpringApplication.addListeners(...) or in META-INF/spring.factories, as shown in the next section.6. A Complete Example: Watching an Order Service Start
Let's build a small order service that logs every important phase. It uses one early listener registered by hand, two bean listeners, a cache warm-up runner and a service with a @PostConstruct method. Create a project with the Spring Web dependency (spring-boot-starter-webmvc) on Spring Boot 4.2 and Java 25.
6.1 The Main Class with an Early Listener
package com.javabytechie.shop.order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
@SpringBootApplication
public class OrderServiceApplication {
private static final Logger log = LoggerFactory.getLogger(OrderServiceApplication.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrderServiceApplication.class);
// Registered by hand because this event fires before any bean exists
app.addListeners(event -> {
if (event instanceof ApplicationEnvironmentPreparedEvent prepared) {
log.info("[2] Environment ready, active profiles: {}",
String.join(",", prepared.getEnvironment().getActiveProfiles()));
}
});
app.run(args);
}
}
6.2 A Service with an Initialization Callback
package com.javabytechie.shop.order;
import jakarta.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class ProductCatalog {
private static final Logger log = LoggerFactory.getLogger(ProductCatalog.class);
private final Map<String, Product> products = new ConcurrentHashMap<>();
@PostConstruct
void init() {
log.info("[5] ProductCatalog bean created during the context refresh");
}
public void load(Product product) {
products.put(product.sku(), product);
}
public int size() {
return products.size();
}
public record Product(String sku, String name, long priceInCents) {
}
}
6.3 Listeners for the Later Events
package com.javabytechie.shop.order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.server.context.WebServerInitializedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class StartupEventsLogger {
private static final Logger log = LoggerFactory.getLogger(StartupEventsLogger.class);
@EventListener
public void onWebServer(WebServerInitializedEvent event) {
log.info("[6] Web server listening on port {}", event.getWebServer().getPort());
}
@EventListener
public void onRefreshed(ContextRefreshedEvent event) {
log.info("[7] Context refreshed");
}
@EventListener
public void onStarted(ApplicationStartedEvent event) {
log.info("[8] Application started, runners are next");
}
@EventListener
public void onReady(ApplicationReadyEvent event) {
log.info("[10] Application ready, took {} ms", event.getTimeTaken().toMillis());
}
}
WebServerInitializedEvent lives in org.springframework.boot.web.server.context. In Spring Boot 3.x it was in org.springframework.boot.web.context. If an older example does not compile, check this import first.6.4 A Runner That Warms the Catalog
package com.javabytechie.shop.order;
import com.javabytechie.shop.order.ProductCatalog.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class CatalogWarmUpRunner implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(CatalogWarmUpRunner.class);
private final ProductCatalog catalog;
public CatalogWarmUpRunner(ProductCatalog catalog) {
this.catalog = catalog;
}
@Override
public void run(ApplicationArguments args) {
catalog.load(new Product("KB-100", "Mechanical keyboard", 7_999));
catalog.load(new Product("MS-200", "Wireless mouse", 2_499));
log.info("[9] Runner loaded {} products", catalog.size());
}
}
6.5 Run It
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
The output (shortened, with Spring's own lines kept where they mark a phase) shows the order clearly:
[2] Environment ready, active profiles: dev
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
...
:: Spring Boot :: (v4.2.0)
Starting OrderServiceApplication using Java 25 with PID 41872
The following 1 profile is active: "dev"
Tomcat initialized with port 8080 (http)
[5] ProductCatalog bean created during the context refresh
Tomcat started on port 8080 (http) with context path '/'
[6] Web server listening on port 8080
[7] Context refreshed
Started OrderServiceApplication in 1.412 seconds (process running for 1.693)
[8] Application started, runners are next
[9] Runner loaded 2 products
[10] Application ready, took 1424 ms
Read the output from top to bottom and you can see every phase: the early listener runs before the banner, the bean is created while Tomcat is initialized but not yet started, the server starts at the end of the refresh, and the runner runs before the ready event. Your timings and PID will differ.
7. Customizing the Startup
You can change startup behavior with properties or with the SpringApplication API. Properties are usually the better choice, because they can differ per environment without code changes.
| Goal | Property | Code alternative |
|---|---|---|
| Turn off the banner | spring.main.banner-mode=off | app.setBannerMode(Banner.Mode.OFF) |
| Run without a web server | spring.main.web-application-type=none | app.setWebApplicationType(WebApplicationType.NONE) |
| Create beans only when first needed | spring.main.lazy-initialization=true | app.setLazyInitialization(true) |
| Hide the "Starting/Started" info lines | spring.main.log-startup-info=false | app.setLogStartupInfo(false) |
| Activate a profile | spring.profiles.active=dev | app.setAdditionalProfiles("dev") (adds to the active profiles) |
For a fluent style, use SpringApplicationBuilder:
public static void main(String[] args) {
new SpringApplicationBuilder(OrderServiceApplication.class)
.bannerMode(Banner.Mode.OFF)
.profiles("dev")
.run(args);
}
To run code at a fixed point of startup, pick the hook by what you need:
- Change configuration before beans exist: implement
EnvironmentPostProcessorand register it inMETA-INF/spring.factoriesunder the keyorg.springframework.boot.EnvironmentPostProcessor. - Initialize one bean: use a
@PostConstructmethod or a constructor. Do not call other services that might not be ready yet. - Run a one-time task after all beans exist: use
ApplicationRunnerorCommandLineRunner. A failing runner stops the application, which is what you want for essential tasks. - React when the application is fully up: listen to
ApplicationReadyEvent, for example to log a message or register with an external system.
EnvironmentPostProcessor to the org.springframework.boot package. In Spring Boot 3.x it was org.springframework.boot.env.EnvironmentPostProcessor, and that is also the key older spring.factories files use.8. Measuring and Improving Startup Time
The "Started ... in 1.412 seconds (process running for 1.693)" line gives two numbers. The first is the time spent inside run(). The second includes JVM start and class loading before main. If the second is much larger, the JVM itself is slow to start, not your beans.
8.1 Finding the Slow Phase
Spring can record every startup step with its duration. Buffer the steps in memory and read them through the Actuator startup endpoint:
public static void main(String[] args) {
SpringApplication app = new SpringApplication(OrderServiceApplication.class);
app.setApplicationStartup(new BufferingApplicationStartup(2048));
app.run(args);
}
management.endpoints.web.exposure.include=health,startup
A POST or GET to /actuator/startup returns a JSON timeline of steps such as spring.beans.instantiate, each with its start time and duration. Sort by duration to find the beans that take the longest to create. BufferingApplicationStartup lives in org.springframework.boot.context.metrics.buffering, and the endpoint needs spring-boot-starter-actuator.
8.2 Making Startup Faster
| Technique | Effect | Trade-off |
|---|---|---|
| Fix slow beans found in the timeline | Often the biggest win: remote calls or large file loads in constructors | None; move the work to a runner or do it on demand |
| Remove unused starters | Fewer auto-configurations and beans | None |
| Lazy initialization | Beans are created on first use | Configuration errors appear later, at the first request |
| JVM AOT cache (Java 25) | Classes are loaded and linked from a cache created in a training run | Extra build step; cache must match the JAR and the Java version |
| GraalVM native image | Starts in milliseconds | Long builds and reflection limits |
To use the AOT cache on Java 25, extract the JAR, do one training run that stops right after the refresh, and start with the cache file:
java -Djarmode=tools -jar order-service.jar extract --destination app
cd app
java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar order-service.jar
java -XX:AOTCache=app.aot -jar order-service.jar
9. How to Fix Common Startup Failures
When startup fails, Spring Boot's failure analyzers print a readable report with a "Description" and an "Action" section. Read that block before the long stack trace. The most common reports:
***************************
APPLICATION FAILED TO START
***************************
Description:
Web server failed to start. Port 8080 was already in use.
Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
| Message or symptom | Phase | Fix |
|---|---|---|
| Port 8080 was already in use | Refresh, web server start | Stop the other process, or set server.port to another port |
| Parameter 0 of constructor in ... required a bean of type ... that could not be found | Refresh, bean creation | Check the class is annotated and inside the scanned packages, or define the bean |
| Failed to configure a DataSource: 'url' attribute is not specified | Refresh, auto-configuration | Add spring.datasource.url, or remove the JPA starter if you do not need a database |
| The dependencies of some of the beans in the application context form a cycle | Refresh, bean creation | Break the cycle; see circular dependencies in Spring |
| Application starts and immediately exits | After runners | No web starter on the classpath, so the type is NONE; add spring-boot-starter-webmvc |
If the report is not enough, start with --debug. It prints the conditions evaluation report, which lists every auto-configuration that was applied or skipped and why. The auto-configuration tutorial explains how to read it.
10. Best Practices
- Keep constructors and
@PostConstructmethods fast. They run during the refresh, and every slow one delays the whole application. - Use runners for essential one-time tasks. A runner runs after all beans exist, and a failure stops the start, so you never serve traffic with missing data.
- Use
ApplicationReadyEventfor "we are up" actions. It fires after the runners, when the application is really ready. - Register early listeners on
SpringApplication. A@Componentlistener never sees events published before the refresh. - Prefer properties over code for banner, lazy initialization and application type, so each environment can choose.
- Measure before you optimize. Use the startup timeline to find the slow beans instead of guessing.
- Read the failure analyzer report first. The Description and Action lines usually name the exact problem.
11. Summary
The Spring Boot application startup process runs inside SpringApplication.run(): it creates the SpringApplication, prepares the environment, prints the banner, creates and prepares the application context, refreshes it to create all beans and start the web server, calls the runners and finally publishes ApplicationReadyEvent. Each phase publishes an event, but only the events from the refresh onward reach @Component listeners. Put one-time startup work in an ApplicationRunner, keep bean creation fast, and use the startup timeline when you need to make startup quicker. Next, see how Spring Boot works internally and how application events can connect your own components.
12. References
Spring Boot Application Startup Process Interview Questions and Answers
Common interview questions on Spring Boot Application Startup Process, from basic to scenario-based, with short answers you can explain in your own words.
Q. In what order are the Spring Boot startup events published?
Answer: ApplicationStartingEvent, ApplicationEnvironmentPreparedEvent, ApplicationContextInitializedEvent and ApplicationPreparedEvent come before the context refresh. During the refresh, a web application publishes WebServerInitializedEvent and then ContextRefreshedEvent. After it come ApplicationStartedEvent with a liveness CORRECT event, then the runners, then ApplicationReadyEvent with a readiness ACCEPTING_TRAFFIC event. A failed start publishes ApplicationFailedEvent instead.
Q. Why does an @EventListener method for ApplicationStartingEvent never run?
Answer: The listener is a bean, and beans are created during the context refresh. ApplicationStartingEvent and the other three early events are published before the refresh, when the listener object does not exist yet. Register such listeners with SpringApplication.addListeners() or in META-INF/spring.factories under org.springframework.context.ApplicationListener.
Q. Should startup logic go in @PostConstruct, a runner or an ApplicationReadyEvent listener?
Answer: Use @PostConstruct only to finish initializing that one bean, because other beans may still be under construction. Use an ApplicationRunner or CommandLineRunner for one-time tasks that need the whole context, such as loading reference data; if it throws, startup fails. Use an ApplicationReadyEvent listener for actions that should happen only once the application is fully up, such as announcing it to another system.
Q. What does the context refresh do, and why is it the slowest phase?
Answer: The refresh processes configuration classes, component scanning and auto-configuration, runs bean factory post-processors, registers bean post-processors, creates the embedded web server, instantiates every non-lazy singleton and finally starts lifecycle beans such as the web server. It is the slowest phase because it creates all the beans, and any bean that opens connections or loads data in its constructor adds directly to the startup time.
Q. Is the embedded web server accepting requests before the runners have finished?
Answer: Yes. The server starts listening at the end of the refresh, before ApplicationStartedEvent and before the runners. A request can therefore arrive while a runner is still loading data. That is why readiness is reported only after the runners: a load balancer or Kubernetes readiness probe that checks the readiness state will not send traffic until ACCEPTING_TRAFFIC is published.
Q. The log says "Started in 2 seconds (process running for 9 seconds)". Where did the other 7 seconds go?
Answer: The first number covers only the time inside SpringApplication.run(). The second is measured from JVM start, so the gap is spent before main runs: JVM start, class loading and anything a launcher or agent does first. Look at JVM options, Java agents and container CPU limits, and consider the Java 25 AOT cache, rather than tuning beans.
Q. Your service takes 40 seconds to start and Kubernetes restarts it before it is ready. How do you investigate and fix this?
Answer: First, stop the restarts: configure a startup probe (or a longer initial delay) so liveness checks wait for startup. Then measure with BufferingApplicationStartup and the /actuator/startup endpoint to find the slowest steps, which are usually beans that call remote systems or load large data in constructors. Move that work to a runner or make it lazy, remove unused starters, and consider the AOT cache. Avoid simply enabling global lazy initialization, because it hides configuration errors until the first request.