This project demonstrates the lifecycle of Spring beans, showing the different phases a bean goes through from creation to destruction, and the various ways to hook into these lifecycle events.
Spring beans go through several phases during their lifecycle:
- Instantiation: The bean is created using its constructor
- Property Population: Spring injects dependencies and sets properties
- Initialization: Post-processing and custom initialization methods are called
- Usage: The bean is available for use in the application
- Destruction: Cleanup methods are called when the container is shutting down
This demo shows three different approaches to hooking into the bean lifecycle:
- Annotation-based: Using
@PostConstructand@PreDestroyannotations - Interface-based: Implementing
InitializingBeanandDisposableBeaninterfaces - Configuration-based: Using
initMethodanddestroyMethodin@Beandefinition
It also demonstrates the difference between singleton beans (default) and prototype beans.
AnnotationService.java: Demonstrates lifecycle hooks using annotationsInterfaceService.java: Demonstrates lifecycle hooks using Spring interfacesConfigService.java: Demonstrates lifecycle hooks using custom method namesBeanConfig.java: Configuration class that defines the ConfigService bean with custom init/destroy methodsPrototypeService.java: Demonstrates lifecycle for prototype-scoped beansSpringBeanLifecycleApplication.java: Main application that runs the demo
All beans show constructor execution during this phase.
This phase happens automatically (dependency injection).
Each service demonstrates a different way to hook into this phase:
AnnotationService: Uses@PostConstructInterfaceService: ImplementsafterPropertiesSet()fromInitializingBeanConfigService: Uses a custom method specified in@Bean(initMethod="customSetup")
The application is running and beans are available for use.
Each service demonstrates a different way to hook into this phase:
AnnotationService: Uses@PreDestroyInterfaceService: Implementsdestroy()fromDisposableBeanConfigService: Uses a custom method specified in@Bean(destroyMethod="customCleanup")
To run this demo:
./gradlew bootRunWatch the console output to see the lifecycle phases in action. The application will:
- Start the Spring container
- Show initialization of singleton beans
- Demonstrate prototype bean creation (multiple instances)
- Manually destroy prototype beans
- Shut down the container, triggering destruction callbacks
- Spring provides multiple ways to hook into bean lifecycle events
- Choose the approach that best fits your application's needs:
- Annotations for simplicity and readability
- Interfaces for strict contracts
- Configuration for external libraries or when you can't modify the source
- Be aware of the differences between singleton and prototype beans, especially regarding destruction callbacks