main method

@SpringBootApplication
public class DemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • Entry Point:
    Execution begins at public static void main(String[] args) — the standard Java application entry point
  • SpringApplication.run(...)
    • Initializes the Spring ApplicationContext (the core container).
    • Starts the embedded servlet container (e.g., Tomcat) if it’s a web app.
    • Loads configuration files and applies auto-configuration.
    • Performs component scanning to discover beans and dependencies
    • More of this down below
Event class발생 시점
ApplicationStartingEvent애플리케이션 시작 직후
ApplicationEnvironmentPreparedEvent환경 준비 직후
ApplicationContextInitializedEvent컨텍스트 초기화 직후
ApplicationPreparedEventBean 등록 전
ApplicationReadyEvent모든 초기화 완료 후
  1. Embedded Server Startup (for web apps)
    • Starts embedded servlet container (Tomcat, Jetty, Undertow) via WebServerFactory.
    • Registers DispatcherServlet to handle web requests.

@SpringBootApplication

Visualization

flowchart TD
    A["public static void main"] --> B["SpringApplication.run(...)"]
    B --> C["@SpringBootApplication"]
    C --> D_sub

    D_sub --> E["ApplicationContext 초기화 (All beans are registered, initialized, and DI is performed)"]
    E --> F["내장 Tomcat 등 서버 구동"]
    F --> G["클라이언트 요청 대기 상태 진입"]

    subgraph D_sub [구성 어노테이션]
        DA["@EnableAutoConfiguration"]
        DB["@ComponentScan"]
        DC["@SpringBootConfiguration"]
    end

The overall, higher-level flow of the entire application startup

  1. main() method (Application Entry)
    • Starts the entire process.
  2. SpringApplication.run() (The Grand Orchestrator)
    • Does NOT happen in the EXACT order linearly, in reality they are interleaved
    • @SpringBootApplication (meta annotation)
      1. Creation and Initialization of SpringApplication Object
        • `SpringApplication.run(MyApp.class, args);`
          
      2. Creation and Configuration of ApplicationContext (the IoC Container)
        • Chooses ApplicationContext implementation based on WebApplicationType:
          • Servlet apps → AnnotationConfigServletWebServerApplicationContext
          • WebFlux apps → AnnotationConfigReactiveWebServerApplicationContext
          • Non-web apps → AnnotationConfigApplicationContext
        • Runs registered ApplicationContextInitializers for customization.
        • Configures Environment, ApplicationContext, and ResourceLoader.
      3. Auto-Configuration Application (@EnableAutoConfiguration)
        • Applies configurations conditionally (e.g., @ConditionalOnClass, @ConditionalOnMissingBean) to register as bean.
        • Automatically loads and applies configuration candidates based on the classpath.
        • These are not found by your application’s @ComponentScan (they are in separate libraries)
        • @SpringBootApplication - @EnableAutoConfiguration
      4. Component Scanning (@ComponentScan)
      5. Processing of @SpringBootConfiguration
      6. ApplicationContext Refresh (Initialization)
        • ALL BEANS are registered, initialized, and DI is performed
        • Executes CommandLineRunner and ApplicationRunner beans.
        • Publishes lifecycle events received by registered ApplicationListeners.
  3. Embedded Server Startup
    • Transitions the application to a state where it can receive HTTP requests, typically on the default port (8080).
    • The application becomes ready to serve requests.

Summary of SpringApplication.run()

위에 거 옆에 두고 비교해보면 좋음

  1. Preparation: SpringApplication object created, Environment set up, basic ApplicationContext type determined. (Your 2.1 and part of 2.2)
  2. Bean Definition Gathering: This is where the ApplicationContext starts collecting definitions of all the beans it needs to create. This involves:
    • Processing @SpringBootConfiguration (your 2.5)
    • Performing @ComponentScan (your 2.4)
    • Applying @EnableAutoConfiguration (your 2.3) – all contributing bean definitions.
  3. Context Refresh (The Core Construction Phase): Once all bean definitions are gathered, the ApplicationContext “refreshes.” This is a major phase where:
    • The BeanFactory actually creates the bean instances.
    • Dependency Injection is performed.
    • Lifecycle callbacks are executed.
    • Post-processors are applied.
    • CommandLineRunner/ApplicationRunners are run.
    • Events are published. (This covers your 2.6)
  4. Finalization: Embedded server startup. (Your main point 3)

Events

Spring Boot triggers various lifecycle events during its execution. These events allow developers to insert specific actions at crucial moments, such as right after the application starts or just before it shuts down.

EventDescription
ApplicationStartingEventFired immediately after the SpringApplication.run() method is called.
ApplicationEnvironmentPreparedEventOccurs after the Environment (e.g., properties, profiles) has been prepared.
ApplicationContextInitializedEventFired right after the [[IoC (Inversion of Control)#ApplicationContext|ApplicationContext]] has been initialized but before any beans are loaded.
ApplicationPreparedEventTriggered immediately after all preparations are complete, but before the context is refreshed.
ApplicationStartedEventFired right after the ApplicationContext has been refreshed and all beans are loaded.
ApplicationReadyEventOccurs when the application is fully ready to serve requests, after all CommandLineRunner and ApplicationRunner beans have been called.
ApplicationFailedEventFired if the application fails to start due to an exception.
예시: 서버가 켜진 뒤 알림 보내기
@Component
public class ServerReadyNotifier implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 예: 슬랙 메시지 전송
        slackService.send("서버가 준비되었습니다.");
    }
}

Summary

  • main() 메서드의 SpringApplication.run() 호출은 단순한 진입점이 아니라 Spring Boot 전체 실행을 구성하는 중앙 관제탑 역할을 한다.
  • 이 호출 이후 내부적으로는 SpringApplication 인스턴스가 생성되고, run() 메서드를 통해 아래와 같은 주요 단계가 순차적으로 수행된다:
    1. ApplicationContext 준비 (prepareContext)
    2. 자동 설정 로딩 및 Bean 등록
    3. BeanFactoryPostProcessor, BeanPostProcessor 작동
    4. ApplicationContext 초기화 (refresh)
    5. Runner 실행 (callRunners)
  • 이 흐름은 모두 디버깅을 통해 직접 확인 가능하며, refreshContext() 내부에서 최종적으로 context.refresh()를 호출하여 Spring 컨테이너가 완전한 실행 상태로 전환된다.
  • 실습에서는 브레이크포인트를 활용해 Spring의 실행 흐름을 추적하고, 각 메서드 호출 시점의 객체 상태를 확인함으로써 프레임워크 내부 동작에 대한 깊은 이해를 형성할 수 있다.
  • 이러한 실습 기반 학습은 이후 발생할 수 있는 실행 오류나 설정 충돌 이슈에 대한 진단과 문제 해결 역량을 강화하는 데 기초가 된다.