main
method
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- Entry Point:
Execution begins atpublic 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 | 컨텍스트 초기화 직후 |
ApplicationPreparedEvent | Bean 등록 전 |
ApplicationReadyEvent | 모든 초기화 완료 후 |
- Embedded Server Startup (for web apps)
- Starts embedded servlet container (Tomcat, Jetty, Undertow) via
WebServerFactory
. - Registers
DispatcherServlet
to handle web requests.
- Starts embedded servlet container (Tomcat, Jetty, Undertow) via
@SpringBootApplication
- Main notes: @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
main()
method (Application Entry)- Starts the entire process.
SpringApplication.run()
(The Grand Orchestrator)- Does NOT happen in the EXACT order linearly, in reality they are interleaved
- @SpringBootApplication (meta annotation)
- Creation and Initialization of
SpringApplication
Object-
`SpringApplication.run(MyApp.class, args);`
-
- Creation and Configuration of ApplicationContext (the IoC Container)
- Chooses ApplicationContext implementation based on
WebApplicationType
:- Servlet apps →
AnnotationConfigServletWebServerApplicationContext
- WebFlux apps →
AnnotationConfigReactiveWebServerApplicationContext
- Non-web apps →
AnnotationConfigApplicationContext
- Servlet apps →
- Runs registered
ApplicationContextInitializers
for customization. - Configures Environment,
ApplicationContext
, andResourceLoader
.
- Chooses ApplicationContext implementation based on
- 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
- Applies configurations conditionally (e.g.,
- Component Scanning (
@ComponentScan
)- Automatically discovers components (like
@Component
,@Service
, etc.) within specified packages. - @SpringBootApplication - @ComponentScan
- Automatically discovers components (like
- Processing of
@SpringBootConfiguration
- Registers Java-based configuration classes, used for explicit Bean definitions.
- your own explicitly defined
@Bean
methods - @SpringBootApplication - @SpringBootConfiguration
- ApplicationContext Refresh (Initialization)
- ALL BEANS are registered, initialized, and DI is performed
- Executes
CommandLineRunner
andApplicationRunner
beans. - Publishes lifecycle events received by registered
ApplicationListener
s.
- Creation and Initialization of
- 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()
위에 거 옆에 두고 비교해보면 좋음
- Preparation:
SpringApplication
object created,Environment
set up, basicApplicationContext
type determined. (Your 2.1 and part of 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.
- Processing
- 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
/ApplicationRunner
s are run.- Events are published. (This covers your 2.6)
- The
- 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.
Event | Description |
---|---|
ApplicationStartingEvent | Fired immediately after the SpringApplication.run() method is called. |
ApplicationEnvironmentPreparedEvent | Occurs after the Environment (e.g., properties, profiles) has been prepared. |
ApplicationContextInitializedEvent | Fired right after the [[IoC (Inversion of Control)#ApplicationContext |ApplicationContext]] has been initialized but before any beans are loaded. |
ApplicationPreparedEvent | Triggered immediately after all preparations are complete, but before the context is refreshed. |
ApplicationStartedEvent | Fired right after the ApplicationContext has been refreshed and all beans are loaded. |
ApplicationReadyEvent | Occurs when the application is fully ready to serve requests, after all CommandLineRunner and ApplicationRunner beans have been called. |
ApplicationFailedEvent | Fired 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()
메서드를 통해 아래와 같은 주요 단계가 순차적으로 수행된다:- ApplicationContext 준비 (
prepareContext
) - 자동 설정 로딩 및 Bean 등록
- BeanFactoryPostProcessor, BeanPostProcessor 작동
- ApplicationContext 초기화 (
refresh
) - Runner 실행 (
callRunners
)
- ApplicationContext 준비 (
- 이 흐름은 모두 디버깅을 통해 직접 확인 가능하며,
refreshContext()
내부에서 최종적으로context.refresh()
를 호출하여 Spring 컨테이너가 완전한 실행 상태로 전환된다. - 실습에서는 브레이크포인트를 활용해 Spring의 실행 흐름을 추적하고, 각 메서드 호출 시점의 객체 상태를 확인함으로써 프레임워크 내부 동작에 대한 깊은 이해를 형성할 수 있다.
- 이러한 실습 기반 학습은 이후 발생할 수 있는 실행 오류나 설정 충돌 이슈에 대한 진단과 문제 해결 역량을 강화하는 데 기초가 된다.