What Happens Internally When a Spring Boot Application Starts?

2026-11-29来源 dev.toEnglish
What Happens Internally When a Spring Boot Application Starts?

Spring Boot makes application development remarkably simple.

With just a few annotations and a main() method, we can start a complete Java application with dependency injection, embedded Tomcat, database connectivity, REST APIs, security, and much more.

But have you ever wondered what actually happens behind the scenes when we execute this?

@SpringBootApplication public class BankingApplication { public static void main(String[] args) { SpringApplication.run(BankingApplication.class, args); } } 

What happens internally?

  • How does Spring Boot identify the application configuration?
  • When are beans created?
  • How does component scanning work?
  • When does auto-configuration happen?
  • How is embedded Tomcat started?
  • When does the application become ready to receive requests?

Understanding these internals is important for debugging startup failures, improving application startup time, and designing reliable enterprise applications.

Let's walk through the complete startup lifecycle of a Spring Boot application.

1. The Spring Boot Startup Entry Point

Every Spring Boot application starts with the main() method.

public static void main(String[] args) { SpringApplication.run(BankingApplication.class, args); } 

The SpringApplication.run() method is the central entry point responsible for bootstrapping the application.

Internally, Spring Boot performs several important operations:

  1. Creates a SpringApplication instance.
  2. Determines the application type.
  3. Loads initializers and listeners.
  4. Prepares the application environment.
  5. Creates the application context.
  6. Registers bean definitions.
  7. Refreshes the application context.
  8. Starts the embedded web server.
  9. Executes application startup callbacks.

Important: SpringApplication.run() does not simply create objects and start Tomcat. It orchestrates the entire Spring container initialization process.

Spring Boot Startup Lifecycle

2. SpringApplication Object Initialization

Before the application context is created, Spring Boot initializes the SpringApplication object.

SpringApplication app = new SpringApplication(BankingApplication.class); app.run(args); 

During initialization, Spring Boot determines the application type.

Common application types include:

Application Type Description
SERVLET Traditional web applications using Spring MVC
REACTIVE Reactive applications using WebFlux
NONE Non-web applications

For a typical Spring MVC application, Spring Boot identifies the application as a servlet-based application.

It also discovers and prepares:

  • Application context initializers
  • Application listeners
  • Primary application sources
  • Startup configuration

These components participate in different stages of the startup lifecycle.

3. Environment Preparation

Spring Boot prepares the application environment before creating the application context.

The environment contains configuration properties used throughout the application.

For example:

server.port=8081 spring.application.name=banking-service spring.datasource.url=jdbc:postgresql://localhost:5432/banking 

Spring Boot loads configuration from multiple sources, including:

  • application.properties
  • application.yml
  • Environment variables
  • Command-line arguments
  • JVM system properties
  • External configuration sources

The configuration values are exposed through Spring's Environment abstraction.

@Component public class ApplicationConfiguration { private final Environment environment; public ApplicationConfiguration(Environment environment) { this.environment = environment; } public void printPort() { System.out.println( environment.getProperty("server.port") ); } } 

Spring Boot also determines which profiles are active.

spring.profiles.active=dev 

Profile-specific configuration can then be loaded:

application-dev.properties application-qa.properties application-prod.properties 

This allows the same application code to run with different configurations across environments.

Production insight: Configuration should be externalized. Database passwords, API keys, and other secrets should not be hardcoded into application properties or source code.

Spring Boot Environment and Configuration Loading

4. ApplicationContext Creation

After preparing the environment, Spring Boot creates the application context.

The ApplicationContext is the central container of the Spring application.

It manages:

  • Bean definitions
  • Bean instances
  • Dependency injection
  • Bean lifecycle
  • Application events
  • Resource loading
  • Environment access

For a Spring MVC application, Spring Boot typically creates an instance of:

AnnotationConfigServletWebServerApplicationContext 

This context supports annotation-based configuration and embedded servlet web servers.

For a non-web application, a different application context implementation may be selected.

At this stage, the application context exists, but the application is not yet fully initialized.

5. What Does @SpringBootApplication Actually Do?

One of the most important annotations in Spring Boot is:

@SpringBootApplication 

It combines three major annotations.

@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan 

Let's understand each one.

@SpringBootConfiguration

This identifies the class as a Spring Boot configuration class.

It is a specialized form of @Configuration.

@EnableAutoConfiguration

This enables Spring Boot's auto-configuration mechanism.

Spring Boot examines the application environment, classpath, and existing bean definitions to determine which configurations may be appropriate.

@ComponentScan

This enables component scanning.

Spring scans the package containing the main application class and its subpackages for components such as:

@Component @Service @Repository @Controller @RestController 

These components are registered as bean definitions.

Best practice: Place the main application class in a root package so that component scanning can discover the application's components consistently.

@SpringBootApplication Internals

6. Bean Definition Registration

Spring does not immediately create every bean when it discovers a component.

First, it registers bean definitions.

A bean definition contains metadata about a bean, such as:

  • Bean class
  • Scope
  • Dependencies
  • Constructor information
  • Initialization methods
  • Lifecycle configuration

For example:

@Service public class PaymentService { private final PaymentRepository repository; public PaymentService(PaymentRepository repository) { this.repository = repository; } } 

Spring discovers PaymentService and registers its bean definition.

It also discovers the dependency on PaymentRepository.

At this point, Spring has information about the bean, but the actual object may not yet exist.

This distinction is important:

Bean definition registration is not the same as bean instantiation.

7. Auto-Configuration: How Spring Boot Reduces Boilerplate

One of the biggest advantages of Spring Boot is auto-configuration.

Suppose we add the following dependency:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 

Spring Boot can automatically configure several web application components when the relevant conditions are satisfied.

Examples include:

  • Spring MVC infrastructure
  • JSON message converters
  • Embedded servlet web server
  • DispatcherServlet
  • Web-related infrastructure beans

Auto-configuration is driven by conditional configuration classes.

For example:

@Configuration @ConditionalOnClass(DataSource.class) @ConditionalOnMissingBean(DataSource.class) public class CustomDatabaseConfiguration { // Database configuration } 

The conditions determine whether a configuration should be applied.

Spring Boot's auto-configuration mechanism uses conditions such as:

@ConditionalOnClass @ConditionalOnMissingBean @ConditionalOnProperty @ConditionalOnBean 

In modern Spring Boot versions, auto-configuration candidates are discovered through the framework's auto-configuration metadata and imports mechanism.

The actual configurations are evaluated during configuration processing.

Example: Database Auto-Configuration

If the application has the required database libraries and configuration, Spring Boot may configure a DataSource.

spring.datasource.url=jdbc:postgresql://localhost:5432/banking spring.datasource.username=bank_user spring.datasource.password=${DB_PASSWORD} 

Spring Boot can configure the connection pool and related database infrastructure.

If an application provides its own DataSource bean, certain auto-configurations may back off because of conditions such as @ConditionalOnMissingBean.

This is how Spring Boot provides sensible defaults while still allowing customization.

8. ApplicationContext Refresh — The Most Important Phase

The refresh() method is one of the most important operations in the Spring application lifecycle.

It initializes the Spring container and prepares it for use.

During refresh, Spring performs several important operations.

Step 1: Prepare the BeanFactory

Spring creates and prepares the internal BeanFactory, which is responsible for managing bean definitions and bean creation.

Step 2: Execute BeanFactoryPostProcessors

These processors can modify bean definitions before regular beans are instantiated.

An important example is:

ConfigurationClassPostProcessor 

It processes configuration classes and handles annotations such as:

@Configuration @ComponentScan @Bean @Import 

This is where much of the configuration class processing and component scanning takes place.

Step 3: Register BeanPostProcessors

Spring registers processors that can customize beans before and after initialization.

Examples include processors involved in:

  • Dependency injection
  • AOP proxy creation
  • Annotation processing
  • Lifecycle callbacks

Step 4: Instantiate Singleton Beans

Spring creates non-lazy singleton beans.

It resolves dependencies and injects them into constructors, fields, or setter methods.

Step 5: Initialize Beans

Spring invokes applicable initialization callbacks.

For example:

@PostConstruct public void initialize() { System.out.println("PaymentService initialized"); } 

Other initialization mechanisms include:

InitializingBean 

and custom initialization methods.

Step 6: Complete Context Refresh

Spring completes the refresh process and publishes the relevant lifecycle events.

For a web application, the embedded web server is also initialized during this overall refresh process.

Inside ApplicationContext.refresh()

9. Dependency Injection and Bean Creation

Let's consider a simple banking application.

@RestController public class PaymentController { private final PaymentService paymentService; public PaymentController(PaymentService paymentService) { this.paymentService = paymentService; } } 
@Service public class PaymentService { private final PaymentRepository repository; public PaymentService(PaymentRepository repository) { this.repository = repository; } } 
@Repository public class PaymentRepository { } 

Spring resolves the dependency chain:

PaymentController | v PaymentService | v PaymentRepository 

When creating the controller, Spring first resolves its required PaymentService.

While creating the service, Spring resolves its PaymentRepository.

Once the dependencies are available, Spring constructs the objects and injects them.

The resulting beans are managed by the Spring container.

For singleton-scoped beans, Spring normally creates one shared instance per bean definition within the application context.

Important: Singleton scope does not mean one object across the entire JVM. It means one managed instance per bean definition per Spring container.

10. Embedded Tomcat Startup

For a typical Spring Boot web application, embedded Tomcat is started as part of application context refresh.

Spring Boot creates a servlet web server through a ServletWebServerFactory.

For example:

TomcatServletWebServerFactory 

The web server infrastructure configures:

  • Server port
  • Connectors
  • Servlet context
  • Filters
  • Servlet registrations

Spring MVC also configures the DispatcherServlet, which acts as the front controller for incoming HTTP requests.

A typical request flow is:

Client | v Embedded Tomcat | v DispatcherServlet | v Controller | v Service | v Repository | v Database 

Once the web server has successfully started, the application can begin accepting HTTP requests.

Spring Boot Embedded Tomcat Architecture

11. ApplicationRunner and CommandLineRunner

After the application context has been refreshed and the application startup process has reached the runner phase, Spring Boot executes registered startup runners.

Two common interfaces are:

CommandLineRunner 

and

ApplicationRunner 

Example:

@Component public class BankingStartupRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { System.out.println( "Banking application startup completed" ); } } 

These interfaces are useful for executing startup tasks such as:

  • Loading reference data
  • Validating startup configuration
  • Initializing application-specific resources
  • Performing controlled startup checks

Use them carefully.

Long-running operations inside startup runners can delay application readiness.

For example, loading millions of records during startup can significantly increase deployment time.

12. When Is the Application Actually Ready?

Spring Boot publishes several application lifecycle events.

Some important events include:

Event Meaning
ApplicationStartingEvent Startup process begins
ApplicationEnvironmentPreparedEvent Environment is prepared
ApplicationContextInitializedEvent Context initialization phase
ApplicationPreparedEvent Context prepared before refresh
ContextRefreshedEvent Application context refreshed
ApplicationStartedEvent Application startup phase completed
ApplicationReadyEvent Application is ready for application-level traffic

The exact sequence and event details can vary by Spring Boot version and application type.

The important distinction is:

Context refreshed does not necessarily mean the application is fully ready.

The application may still need to execute startup runners and complete other readiness-related initialization.

In a production environment, readiness should also account for the application's ability to serve requests safely.

For example, a banking service may need to verify that essential dependencies are available before being marked ready.

13. Complete Spring Boot Startup Flow

Let's summarize the entire lifecycle.

main() | v SpringApplication.run() | v Create SpringApplication | v Determine Application Type | v Prepare Environment | v Create ApplicationContext | v Register Bean Definitions | v Process Configuration Classes | v Evaluate Auto-Configuration | v ApplicationContext.refresh() | v Create and Initialize Beans | v Start Embedded Tomcat | v ApplicationStartedEvent | v Execute ApplicationRunner / CommandLineRunner | v ApplicationReadyEvent | v Application Ready 

Complete Spring Boot Startup Internals

14. Why Does Spring Boot Startup Sometimes Fail?

Understanding the startup lifecycle helps us identify common failures.

BeanCreationException

A bean cannot be created because of an invalid configuration or dependency.

NoSuchBeanDefinitionException

Spring cannot find a required bean.

Possible causes include missing component scanning, missing configuration, or an unavailable dependency.

Circular Dependency

Two or more beans depend on each other in a way that prevents normal construction.

Constructor-based circular dependencies generally fail during bean creation.

Port Already in Use

The embedded server cannot bind to the configured port.

server.port=8080 

Another process may already be using that port.

Database Connection Failure

The application may fail while initializing database infrastructure or connecting to a required database.

Auto-Configuration Conflict

Multiple configurations may attempt to provide incompatible beans or infrastructure.

The Spring Boot condition evaluation report can help identify why an auto-configuration was applied or skipped.

Run the application with:

java -jar banking-service.jar --debug 

The debug output can provide useful auto-configuration diagnostics.

15. Production Considerations for Spring Boot Startup

In enterprise applications, startup behavior is not just a technical detail.

It directly affects deployment reliability and service availability.

Consider the following practices:

  • Keep startup initialization lightweight.
  • Avoid unnecessary eager initialization of expensive resources.
  • Use lazy initialization only when its trade-offs are understood.
  • Externalize environment-specific configuration.
  • Validate critical configuration early.
  • Use readiness and liveness probes appropriately.
  • Avoid blocking startup with long-running data loading.
  • Monitor startup duration and initialization failures.
  • Ensure essential downstream dependencies are available before readiness when required.

For Kubernetes and OpenShift deployments, startup probes, readiness probes, and liveness probes should be configured according to the application's actual startup and health behavior.

A slow-starting application should not be repeatedly restarted simply because it needs additional time to initialize.

Final Thoughts

Spring Boot simplifies application development, but internally it performs a sophisticated sequence of operations.

From environment preparation and configuration processing to bean creation, dependency injection, embedded server startup, and application readiness, every phase plays an important role.

Understanding this lifecycle helps Java developers:

  • Debug startup failures faster
  • Understand dependency injection deeply
  • Customize auto-configuration
  • Improve startup performance
  • Design reliable microservices
  • Troubleshoot production deployments

The next time you execute SpringApplication.run(), remember that you are triggering the initialization of an entire application infrastructure — not just starting a Java program.

Spring Boot makes configuration easier, but understanding its internals makes you a better Spring Boot engineer.

Author: Ram The Architect (RTA)

Follow me for more practical insights on Java 21 | Spring Boot | Microservices | Apache Kafka | AWS | System Design | GenAI

Github: https://github.com/Ramu-fsd/enterprise-banking-microservices
Linkedin: https://www.linkedin.com/in/ramuboya/

Technology: Java 21 | Concurrency | Multithreading | CompletableFuture | Spring Boot | Microservices

Java #SpringBoot #SpringFramework #JavaDeveloper #Microservices #BackendDevelopment #SoftwareArchitecture #DevOps #Fintech

原文:https://www.a8q9.cn/en/article/what-happens-internally-when-a-spring-boot-application-starts-24aad7.html

相关文章