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

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

This document details the comprehensive execution order of the Spring Boot application bean lifecycle, encompassing related methods at each stage.

Phase 1: Bootstrapping (JVM & Spring Boot Initialization)

  1. JVM Initialization: The Java Virtual Machine (JVM) starts and loads the main application class (containing public static void main(String[] args)).
  2. SpringApplication Execution: SpringApplication.run() initiates the application context creation. (Related Method: SpringApplication.run())
  3. Environment Configuration: The application loads settings from system properties, environment variables, application.properties/yml files, and command-line arguments. Active and default profiles are determined. (Related Methods: ConfigurableEnvironment#setActiveProfiles(), PropertySourcesPropertyResolver#getProperty())
  4. Application Type Determination: Spring identifies the application type (web or non-web). This determines the appropriate application context: AnnotationConfigServletWebServerApplicationContext (web) or AnnotationConfigApplicationContext (non-web). (Related Method: SpringApplication#determineWebApplicationType())
  5. Auto-Configuration & SpringFactoriesLoader: Spring automatically registers dependencies found on the classpath (via META-INF/spring.factories). (Related Method: SpringFactoriesLoader#loadFactoryNames())
  6. Application Run Listeners: SpringApplicationRunListeners are triggered, firing events like ApplicationStartingEvent and ApplicationEnvironmentPreparedEvent. (Related Methods: SpringApplicationRunListeners#starting(), SpringApplicationRunListeners#environmentPrepared())

Phase 2: Context Initialization & Bean Lifecycle

  1. ApplicationContext Creation: The ApplicationContext is created, and beans are scanned using annotations like @ComponentScan and @Configuration. (Related Method: AnnotationConfigApplicationContext#register())
  2. Bean Definition Loading: Spring processes bean definitions from configuration classes, XML files, or component scanning. Note: Bean instances are not created yet. (Related Method: BeanDefinitionRegistry#registerBeanDefinition())
  3. Bean Instantiation: Beans are instantiated using constructor injection or factory methods. (Related Method: InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation())
  4. Lifecycle Aware Bean Processing: Beans implementing lifecycle interfaces (e.g., BeanNameAware, BeanFactoryAware, EnvironmentAware) are processed. (Related Methods: BeanNameAware#setBeanName(), BeanClassLoaderAware#setBeanClassLoader(), BeanFactoryAware#setBeanFactory(), EnvironmentAware#setEnvironment(), EmbeddedValueResolverAware#setEmbeddedValueResolver(), etc.)
  5. Conditional Beans & Profiles: Beans marked with @Conditional or @Profile are evaluated and conditionally created based on specified conditions or active profiles. (Related Methods: Condition#matches(), ConfigurableEnvironment#getActiveProfiles())
  6. Pre-Initialization Post-Processing: BeanPostProcessor#postProcessBeforeInitialization() methods are executed.
  7. Custom Initialization: Custom initialization logic is executed using @PostConstruct, InitializingBean.afterPropertiesSet(), or the init-method attribute in @Bean annotations. (Related Methods: InitializingBean#afterPropertiesSet(), @PostConstruct)
  8. Post-Initialization Post-Processing: BeanPostProcessor#postProcessAfterInitialization() methods are executed.

Phase 3: Application Startup Completion

  1. ApplicationContext Refresh: The ApplicationContext is refreshed, completing dependency injection. The ContextRefreshedEvent is fired. (Related Method: AbstractApplicationContext#refresh())
  2. Embedded Web Server Start (if applicable): If it's a web application, the embedded server (Tomcat, Jetty, Undertow) starts and binds to a port. ServletContextInitializer and WebApplicationInitializer are executed (for servlet-based apps). (Related Method: ConfigurableWebServerApplicationContext#start())
  3. CommandLineRunner & ApplicationRunner Execution: Beans implementing CommandLineRunner or ApplicationRunner are executed, performing post-startup tasks. (Related Methods: CommandLineRunner#run(), ApplicationRunner#run())
  4. ApplicationReadyEvent: The ApplicationReadyEvent is fired, signaling that the application is fully initialized and ready to handle requests. (Related Method: ApplicationListener#onApplicationEvent(ApplicationReadyEvent))

Phase 4: Bean Destruction & Application Shutdown

  1. Graceful Shutdown: The shutdown process begins, controlled by spring.lifecycle.timeout-per-shutdown-phase. (Related Method: SpringApplication#setRegisterShutdownHook(true))
  2. Pre-Destruction Processing: DestructionAwareBeanPostProcessor#postProcessBeforeDestruction() methods are executed.
  3. Custom Cleanup: Custom cleanup logic is performed using DisposableBean.destroy(), @PreDestroy methods, or the destroy-method attribute in @Bean annotations. (Related Methods: DisposableBean#destroy(), @PreDestroy)
  4. ApplicationContext Closure: The ApplicationContext closes, firing the ContextClosedEvent. (Related Method: ConfigurableApplicationContext#close())
  5. Custom Exit Codes: SpringApplication.exit() can be used to set custom exit codes (using ExitCodeGenerator). (Related Method: SpringApplication#exit())

Phase 5: Advanced Considerations

  • Lazy Initialization (@Lazy): Beans are created only when accessed. (Related Method: DefaultListableBeanFactory#setAllowBeanDefinitionOverriding(false))
  • Circular Dependency Handling: Use @Lazy, setter injection, or @DependsOn to manage circular dependencies. (Related Method: AbstractAutowireCapableBeanFactory#doResolveDependency())
  • FactoryBean Mechanism: Allows for dynamic bean creation. (Related Method: FactoryBean#getObject())
  • Spring Boot Actuator (if enabled): Provides endpoints for monitoring and management (/actuator/health, /actuator/shutdown, /actuator/metrics). (Related Method: HealthIndicator#health())
  • Performance Optimizations: Reduce startup time with spring.main.lazy-initialization=true and tune garbage collection.
  • Custom Application Listeners (ApplicationListener): Allows hooking into startup/shutdown events. (Related Method: ApplicationListener#onApplicationEvent())

Summary of Execution Order:

  1. Bootstrapping: JVM → SpringApplication.run() → Auto-Configuration → Context Creation
  2. Context Initialization: Bean Instantiation → Lifecycle Hooks → Dependency Injection
  3. Application Startup: Web Server Starts → Runners Execute → Application Ready
  4. Shutdown Phase: Pre-Destruction Callbacks → Cleanup → Context Closes

This detailed breakdown provides a comprehensive understanding of the Spring Boot bean lifecycle and its execution order. Understanding this order is crucial for debugging, optimizing, and extending Spring Boot applications.

The above is the detailed content of spring-: spring-boot-application-bean-lifecycle-comprehensive-execution-order-with-related-methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.