Behind SpringApplication.run()

Behind SpringApplication.run()

Spring Boot is designed to simplify Java application development by reducing boilerplate and automating configuration. While most developers interact with it through annotations, understanding what happens behind the scenes is just as important.

In this post, we'll explore the internal working of Spring Boot step by step, from application startup to context initialization. Along the way, we'll highlight the key concepts and components that make Spring Boot fast, flexible, and production-ready.

Step 1: Application Entry Point

  • Application starts with the main() method.
  • SpringApplication.run() is called to bootstrap the application.

Step 2: SpringApplication Initialization

  • Creates a SpringApplication instance.
  • Detects the application type (web, reactive, non-web).
  • Registers default ApplicationListeners and ApplicationInitializers.

Step 3: Environment Preparation

  • Creates a ConfigurableEnvironment.
  • Loads property sources- application.properties / application.yml.
  • System environment variables.
  • JVM system properties (-D).
  • Command-line arguments.
  • Resolves and activates profiles (e.g., dev, prod).
  • Prepares the environment for use in the ApplicationContext.

Step 4: IoC Container Setup (ApplicationContext)

  • Creates the appropriate ApplicationContext.
  • AnnotationConfigServletWebServerApplicationContext for web apps.
  • Sets the environment into the context.
  • Loads bean definitions from - Classpath component scanning.
  • @Configuration classes.
  • Auto-configuration classes.

Step 5: Auto-Configuration

  • Enables @EnableAutoConfiguration via @SpringBootApplication.
  • Loads auto-configuration classes from META-INF/spring.factories.
  • Applies conditional logic using:-
  • @ConditionalOnClass.
  • @ConditionalOnMissingBean.
  • @ConditionalOnProperty.

Step 6: Bean Creation & Dependency Injection

  • Instantiates and registers all beans.
  • Injects dependencies via- @Autowired , Constructor or setter injection.
  • Handles lifecycle methods:- @PostConstruct, @PreDestroy.
  • Applies AOP (e.g., @Transactional, @Async).

Step 7: Embedded Web Server Startup (if Web App)

  • Auto-configures and starts an embedded server (Tomcat, Jetty, or Undertow).
  • Registers DispatcherServlet and other Spring MVC components.
  • Prepares the HTTP layer to accept incoming requests.

Step 8: Event Publishing

  • Publishes core lifecycle events like - ApplicationStartingEvent
  • ApplicationEnvironmentPreparedEvent.
  • ApplicationContextInitializedEvent.
  • ApplicationStartedEvent.
  • ApplicationReadyEvent.

Step 9: Runner Execution

  • Executes beans implementing.
  • CommandLineRunner.
  • ApplicationRunner.
  • Ideal for executing startup logic or scripts.

Step 10: Application Ready

  • Application is now fully started.

Spring Boot Key Terms --

1. Inversion of Control (IoC) - Inversion of Control (IoC) is a design principle where control over object creation and dependency management is transferred from your code to a framework (like Spring).

Rather than your code creating and managing objects, Spring does it for you.

Real-World Analogy: Restaurant

You don't cook your meal at a restaurant. You just place an order. The kitchen prepares and serves it to you. In Spring: -

  • You declare what you need.
  • Spring (the kitchen) creates and provides the necessary objects (beans).

Example

Without IoC:

PaymentService service = new PaymentService(new CreditCardProcessor());        

With Spring IoC:

@Component
public class CreditCardProcessor {}

@Service
public class PaymentService {

    private final CreditCardProcessor processor;

    @Autowired
   public PaymentService(CreditCardProcessor processor) {
        this.processor = processor;
    }
}        

Spring creates and injects the CreditCardProcessor bean automatically.

2. Dependency Injection (DI) - Dependency Injection (DI) is a technique used by Spring to provide the required objects (dependencies) to a class rather than the class creating them itself.

Types of DI in Spring

  • Constructor Injection (Recommended).
  • Setter Injection.
  • Field Injection

Real-World Analogy: Car and Engine

You're building a car but don’t make the engine yourself. A company provides and installs it. In Spring - Your class (car) receives its needed components (engine) from the container.

Example

@Component
public class EmailSender {

    public void send(String email, String msg) {
        System.out.println("Email to " + email + ": " + msg);
    }
}

@Service
public class OrderService {

    private final EmailSender emailSender;

    @Autowired
    public OrderService(EmailSender emailSender) {
        this.emailSender = emailSender;
    }

    public void placeOrder() {
        emailSender.send("user@example.com", "Order confirmed!");
    }
}        

3. Bean - A Bean is any object that is managed by the Spring container.

  • Spring- Creates it.
  • Injects it where needed.
  • Manages its lifecycle.

Real-World Analogy: Employees in a Company -

You don’t hire each employee personally. The HR department (Spring) handles hiring, assigning roles, and onboarding.

In Spring: - Declare your components, and Spring takes care of the rest.

Ways to Define Beans

  • Annotation-Based

@Component
public class NotificationService {}

Or using specialization:
@Service
@Repository
@Controller        

  • Java Config

@Configuration
public class AppConfig {

    @Bean
    public NotificationService notificationService() {
        return new NotificationService();
    }
}        

4. ApplicationContext - ApplicationContext is the central interface in Spring that represents the IoC container.The ApplicationContext in Spring Boot is a central interface representing the Spring IoC (Inversion of Control) container. It is responsible for managing the lifecycle and dependencies of "beans," which are the objects that form the backbone of a Spring application.

The ApplicationContext is the core of Spring's IoC

It manages beans and offers additional features like:

  • Dependency injection.
  • Event handling.
  • Resource loading.
  • Message internationalization (i18n).

Real-World Analogy: Office Manager

Think of it like a company’s manager who:

  • Hires employees (creates beans).
  • Assigns tasks (injects dependencies).
  • Shares messages (event handling).
  • Manages office resources (files, URLs).

Common Implementations:

  • AnnotationConfigApplicationContext – For Java-based configs.
  • ClassPathXmlApplicationContext – For XML-based configs.
  • AnnotationConfigServletWebServerApplicationContext – Used in Spring Boot web apps.

Example Standalone App -

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

MyService service = context.getBean(MyService.class);
service.doWork();        

5. Profiles - Profiles let you define different configurations for different environments like:

  • dev (development).
  • test.
  • prod (production).

You can activate a profile in your application.properties or through environment variables to load only the beans or settings relevant to that environment.

Real-world Analogy

Like wearing different outfits for different weather — same person, different gear.

Example

application.properties

spring.profiles.active=dev

You can have separate files like:

application-dev.properties

application-prod.properties        

Each with different database settings or logging levels.

6. CommandLineRunner / ApplicationRunner - These are interfaces in Spring Boot used to run custom logic after the application has started and the Spring context is fully loaded.

  • CommandLineRunner gives you the raw String[] args.
  • ApplicationRunner gives you a more structured ApplicationArguments object.

Use Cases -

  • Preloading test data.
  • Sending a startup notification.
  • Validating configuration.
  • Running a background task once.

Real-world Analogy

Think of it like a checklist that runs right after a machine boots up — for testing or setup.

7. Embedded Web Server - Spring Boot applications include a web server (like Tomcat or Jetty) built-in. This means you don't need to deploy your app to an external server — just run the JAR file and it's all set.

Real-world Analogy

Imagine buying a car with the engine already installed. You don't need to build or attach it separately.

Default Behavior - When you include spring-boot-starter-web, Spring Boot starts an embedded Tomcat server on localhost:8080.

You can also change the port:

properties.server.port=9090        

Benefit - Simplifies deployment — run as a standalone JAR and Great for microservices or cloud-native apps.

8. Application Events - Spring Boot can publish lifecycle events such as

  • Context started.
  • Application ready.
  • Context closed.

You can listen to these events to perform certain actions at the right time in the app lifecycle.

Real-world Analogy - Like notifications you receive on your phone when something important happens — "Your package is shipped", "Your app is ready", etc.


Spring Boot takes care of many things automatically, but understanding what’s happening behind the scenes can help you write cleaner and more adaptable applications.

In this post, we looked at how Spring Boot starts up and explored some of the important concepts that support its internal process. Having this foundation makes it easier to work with the framework more effectively, especially when dealing with configurations and annotations.




To view or add a comment, sign in

More articles by VIMAL SHARMA

Others also viewed

Explore content categories