DEV Community

Hunor Vadasz-Perhat
Hunor Vadasz-Perhat

Posted on

spring-013: spring-boot-application-bean-lifecycle-comprehensive-execution-order-with-related-methods

1️⃣ Bootstrapping Phase (JVM & Spring Boot Startup)

  1. JVM starts and loads the main class (public static void main(String[] args)).
  2. SpringApplication.run() executes to initialize the application. 💡 Related method: SpringApplication.run()
  3. Environment Setup:
    • Loads system properties, environment variables, application.properties/yml, and command-line arguments.
    • Determines active and default profiles. 💡 Related method: ConfigurableEnvironment#setActiveProfiles(), PropertySourcesPropertyResolver#getProperty()
  4. Application Type Determined:
    • Web AppAnnotationConfigServletWebServerApplicationContext
    • Non-Web AppAnnotationConfigApplicationContext 💡 Related method: SpringApplication#determineWebApplicationType()
  5. AutoConfiguration & SpringFactoriesLoader:
    • Automatically registers dependencies from the classpath (META-INF/spring.factories). 💡 Related method: SpringFactoriesLoader#loadFactoryNames()
  6. SpringApplicationRunListeners Triggered:
    • Fires ApplicationStartingEvent, ApplicationEnvironmentPreparedEvent. 💡 Related method: SpringApplicationRunListeners#starting(), SpringApplicationRunListeners#environmentPrepared()

2️⃣ Context Initialization & Bean Lifecycle

  1. ApplicationContext is created and beans are scanned (@ComponentScan, @Configuration). 💡 Related method: AnnotationConfigApplicationContext#register()
  2. Bean Definition is Loaded (Metadata Processing):
    • Spring reads bean definitions from configuration files (@Configuration), XML files, or component scanning (@Component).
    • This is a metadata processing step—no instances are created yet. 💡 Related method: BeanDefinitionRegistry#registerBeanDefinition()
  3. Beans are instantiated (Object Creation):
    • Constructor-based instantiation.
    • Factory method instantiation. 💡 Related method: InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation()
  4. Lifecycle Aware Beans are processed:
    • setBeanName() (BeanNameAware). 💡 Related method: BeanNameAware#setBeanName(String name)
    • setBeanClassLoader() (BeanClassLoaderAware). 💡 Related method: BeanClassLoaderAware#setBeanClassLoader(ClassLoader classLoader)
    • setBeanFactory() (BeanFactoryAware). 💡 Related method: BeanFactoryAware#setBeanFactory(BeanFactory factory)
    • setEnvironment() (EnvironmentAware). 💡 Related method: EnvironmentAware#setEnvironment(Environment environment)
    • setEmbeddedValueResolver() (EmbeddedValueResolverAware). 💡 Related method: EmbeddedValueResolverAware#setEmbeddedValueResolver(StringValueResolver resolver)
    • setResourceLoader(), setApplicationEventPublisher(), setMessageSource(), setApplicationContext(), setServletContext() (if applicable).
  5. Conditional Beans & Profiles Applied (@Conditional, @Profile). 💡 Related method: Condition#matches(), ConfigurableEnvironment#getActiveProfiles()
  6. Post-processing before initialization: 💡 Related method: BeanPostProcessor#postProcessBeforeInitialization()
  7. Custom Initialization:
    • @PostConstruct
    • InitializingBean.afterPropertiesSet()
    • init-method (if defined in @Bean). 💡 Related method: InitializingBean#afterPropertiesSet(), @PostConstruct
  8. Post-processing after initialization: 💡 Related method: BeanPostProcessor#postProcessAfterInitialization()

3️⃣ Application Startup Completion

  1. ApplicationContext Refreshes:
    • Dependency injection is completed.
    • Fires ContextRefreshedEvent. 💡 Related method: AbstractApplicationContext#refresh()
  2. Embedded Web Server Starts (if applicable):
    • Tomcat, Jetty, or Undertow binds to a port.
    • ServletContextInitializer and WebApplicationInitializer execute for servlet-based apps. 💡 Related method: ConfigurableWebServerApplicationContext#start()
  3. CommandLineRunner & ApplicationRunner Execute:
    • Runs post-startup logic. 💡 Related method: CommandLineRunner#run(), ApplicationRunner#run()
  4. ApplicationReadyEvent Fires:
    • Application is fully initialized and ready to serve requests. 💡 Related method: ApplicationListener#onApplicationEvent(ApplicationReadyEvent)

4️⃣ Bean Destruction & Application Shutdown

  1. Graceful Shutdown Begins:
    • Controlled via spring.lifecycle.timeout-per-shutdown-phase. 💡 Related method: SpringApplication#setRegisterShutdownHook(true)
  2. Pre-Destruction Processing: 💡 Related method: DestructionAwareBeanPostProcessor#postProcessBeforeDestruction()
  3. Custom Cleanup:
    • DisposableBean.destroy().
    • @PreDestroy method.
    • Custom destroy-method (if defined in @Bean). 💡 Related method: DisposableBean#destroy(), @PreDestroy
  4. ApplicationContext Closes:
    • Fires ContextClosedEvent. 💡 Related method: ConfigurableApplicationContext#close()
  5. SpringApplication.exit() can be used to set custom exit codes (ExitCodeGenerator). 💡 Related method: SpringApplication#exit()

5️⃣ Advanced Considerations (Optimizations & Monitoring)

Lazy Initialization (@Lazy) – Beans are only created when accessed.

💡 Related method: DefaultListableBeanFactory#setAllowBeanDefinitionOverriding(false)

Circular Dependency Handling – Use @Lazy, setter injection, or @DependsOn.

💡 Related method: AbstractAutowireCapableBeanFactory#doResolveDependency()

FactoryBean Mechanism – Provides dynamic bean creation.

💡 Related method: FactoryBean#getObject()

Spring Boot Actuator (if enabled):

  • /actuator/health, /actuator/shutdown, /actuator/metrics. 💡 Related method: HealthIndicator#health()Performance Optimizations:
  • Reduce startup time with spring.main.lazy-initialization=true.
  • Tune garbage collection (-XX:+UseG1GC). ✅ Custom Application Listeners (ApplicationListener<>) – Hook into startup/shutdown events. 💡 Related method: ApplicationListener#onApplicationEvent()

📌 Final Summary: Ultimate Execution Order

🟢 Bootstrapping: JVM → SpringApplication.run() → AutoConfiguration → Context Creation

🟠 Context Initialization: Beans Instantiated → Lifecycle Hooks → Dependency Injection

🔵 Application Startup: Web Server Starts → Runners Execute → Application Ready

🟣 Shutdown Phase: Pre-Destruction Callbacks → Cleanup → Context Closes


Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay