00:00

Spring Boot Application Startup Process

Last updated:

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.
Analogy: Think of opening a restaurant in the morning. First the manager reads today's notes (environment), then unlocks the kitchen (context), then the cooks prepare every station (beans) and switch on the stoves (web server). Only when the prep list is done (runners) does someone flip the sign to "Open" (ready event).

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:

SituationWhat the startup sequence tells you
You want to warm a cache or load reference data onceUse a runner or an ApplicationReadyEvent listener, not a constructor
A listener for an early event never runsEarly 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 startWhich phase is slow, and when readiness is actually reported
You need a value before beans are createdHook 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.

Spring Boot application startup sequenceThe main method calls SpringApplication.run. Spring Boot first creates the SpringApplication object, then prepares the environment from properties, environment variables and arguments, prints the banner, creates the application context and prepares it. Next it refreshes the context: it processes configuration classes and auto-configuration, creates the singleton beans and starts the embedded web server. Finally it calls ApplicationRunner and CommandLineRunner beans and publishes ApplicationReadyEvent, after which the application accepts traffic. main() SpringApplication .run(args) 1. Set up detect app type, load listeners 2. Environment properties, env vars, profiles, arguments 3. Banner and log startup information 4. Create application context 5. Refresh the context configuration classes and auto-configuration, create singleton beans, start the web server 6. Runners and readiness ApplicationRunner, CommandLineRunner, ApplicationReadyEvent: accepting traffic Usually the slowest phase
SpringApplication.run() moves through six phases; the context refresh creates the 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.

OrderServiceApplication.java
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 is REACTIVE. Otherwise it is NONE, a plain non-web application.
  • Loads early extensions. It reads META-INF/spring.factories files from all JARs to find BootstrapRegistryInitializer, ApplicationContextInitializer and ApplicationListener implementations. 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:

  1. Read the configuration classes. Starting from your main class, Spring processes @SpringBootApplication. Component scanning finds your @Component, @Service, @Repository and @Controller classes, 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.
  2. Run bean factory post-processors. These can change bean definitions before any bean is created, for example to resolve ${...} placeholders.
  3. Register bean post-processors. These wrap or modify beans as they are created, for example to add @Transactional proxies.
  4. 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.
  5. Create all singleton beans. Every non-lazy singleton is instantiated, its dependencies are injected, and its @PostConstruct method runs. This is usually the slowest part.
  6. Finish the refresh. Lifecycle beans start. This is when the web server starts listening and WebServerInitializedEvent is published. Then the context publishes ContextRefreshedEvent.

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:

#EventPublished whenCan a @Component listener receive it?
1ApplicationStartingEventAt the very start of run()No
2ApplicationEnvironmentPreparedEventEnvironment is ready, context not createdNo
3ApplicationContextInitializedEventContext created and initializers applied, no bean definitions loadedNo
4ApplicationPreparedEventBean definitions loaded, refresh about to startNo
5WebServerInitializedEventEmbedded web server is started (web apps only)Yes
6ContextRefreshedEventRefresh finished, all singletons createdYes
7ApplicationStartedEventAfter refresh, before runnersYes
8AvailabilityChangeEvent (LivenessState.CORRECT)Right after ApplicationStartedEventYes
9ApplicationReadyEventAfter all runners have finishedYes
10AvailabilityChangeEvent (ReadinessState.ACCEPTING_TRAFFIC)Right after ApplicationReadyEventYes

If startup fails at any point, ApplicationFailedEvent is published instead of the remaining events.

Why "No" for the first four? A @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

OrderServiceApplication.java
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

ProductCatalog.java
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

StartupEventsLogger.java
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());
    }
}
Version note: In Spring Boot 4, 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

CatalogWarmUpRunner.java
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

Terminal
./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:

Console
[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.

GoalPropertyCode alternative
Turn off the bannerspring.main.banner-mode=offapp.setBannerMode(Banner.Mode.OFF)
Run without a web serverspring.main.web-application-type=noneapp.setWebApplicationType(WebApplicationType.NONE)
Create beans only when first neededspring.main.lazy-initialization=trueapp.setLazyInitialization(true)
Hide the "Starting/Started" info linesspring.main.log-startup-info=falseapp.setLogStartupInfo(false)
Activate a profilespring.profiles.active=devapp.setAdditionalProfiles("dev") (adds to the active profiles)

For a fluent style, use SpringApplicationBuilder:

OrderServiceApplication.java (builder style)
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 EnvironmentPostProcessor and register it in META-INF/spring.factories under the key org.springframework.boot.EnvironmentPostProcessor.
  • Initialize one bean: use a @PostConstruct method or a constructor. Do not call other services that might not be ready yet.
  • Run a one-time task after all beans exist: use ApplicationRunner or CommandLineRunner. 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.
Version note: Spring Boot 4 moved 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:

OrderServiceApplication.java (startup tracking)
public static void main(String[] args) {
    SpringApplication app = new SpringApplication(OrderServiceApplication.class);
    app.setApplicationStartup(new BufferingApplicationStartup(2048));
    app.run(args);
}
application.properties
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

TechniqueEffectTrade-off
Fix slow beans found in the timelineOften the biggest win: remote calls or large file loads in constructorsNone; move the work to a runner or do it on demand
Remove unused startersFewer auto-configurations and beansNone
Lazy initializationBeans are created on first useConfiguration errors appear later, at the first request
JVM AOT cache (Java 25)Classes are loaded and linked from a cache created in a training runExtra build step; cache must match the JAR and the Java version
GraalVM native imageStarts in millisecondsLong 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:

Terminal
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
Version note: Spring Boot 3.3 added support for the JVM's Class Data Sharing (CDS). On Java 25 and later, the Spring Boot documentation recommends the AOT cache instead of CDS.

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:

Console
***************************
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 symptomPhaseFix
Port 8080 was already in useRefresh, web server startStop the other process, or set server.port to another port
Parameter 0 of constructor in ... required a bean of type ... that could not be foundRefresh, bean creationCheck the class is annotated and inside the scanned packages, or define the bean
Failed to configure a DataSource: 'url' attribute is not specifiedRefresh, auto-configurationAdd 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 cycleRefresh, bean creationBreak the cycle; see circular dependencies in Spring
Application starts and immediately exitsAfter runnersNo 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 @PostConstruct methods 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 ApplicationReadyEvent for "we are up" actions. It fires after the runners, when the application is really ready.
  • Register early listeners on SpringApplication. A @Component listener 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