Understanding Spring Bean Scopes and Lifecycles
In the Spring Framework, a 'bean' is an object that is instantiated, assembled, and otherwise managed by the Spring IoC (Inversion of Control) container. Understanding how these beans are created, managed, and destroyed—their lifecycle—and how many instances of a bean exist at any given time—their scope—is fundamental to building robust and efficient Java applications with Spring.
What are Bean Scopes?
Bean scopes define the lifecycle and visibility of a bean within the Spring container. They dictate how many instances of a bean are created and how they are shared among other beans. Spring provides several built-in scopes, each suited for different use cases.
Scope Name | Description | Lifecycle |
---|---|---|
Singleton | A single instance of the bean is created for each Spring IoC container. This is the default scope. | The bean is instantiated when the container starts or when it's first requested. It lives as long as the container. |
Prototype | A new instance of the bean is created every time it's requested from the container. | The container creates the bean and hands it off to the client. The container does not manage the full lifecycle of a prototype bean beyond instantiation. |
Request | A new bean instance is created for each HTTP request. | The bean is created at the start of an HTTP request and destroyed at the end of the request. |
Session | A new bean instance is created for each HTTP session. | The bean is created at the start of an HTTP session and destroyed at the end of the session. |
Application | A single instance of the bean is created for the entire web application (ServletContext). | The bean is created when the web application starts and destroyed when the web application stops. |
The Bean Lifecycle
The lifecycle of a Spring bean involves several stages, from its creation to its destruction. The Spring container manages this process, allowing developers to hook into specific points in the lifecycle to perform custom initialization or cleanup tasks.
Spring beans go through a defined lifecycle managed by the container.
The Spring container is responsible for creating, configuring, and managing the entire lifecycle of your beans, from instantiation to destruction. This allows for predictable behavior and resource management.
The typical lifecycle of a Spring bean includes:
- Instantiation: The bean is created by the container.
- Population of Properties: The container injects dependencies (e.g., via setters or constructor arguments).
- BeanNameAware: If the bean implements
BeanNameAware
, itssetBeanName()
method is called. - BeanFactoryAware: If the bean implements
BeanFactoryAware
, itssetBeanFactory()
method is called. - ApplicationContextAware: If the bean implements
ApplicationContextAware
, itssetApplicationContext()
method is called. - Pre-initialization: Any
BeanPostProcessor
'spostProcessBeforeInitialization()
method is called. - Initialization: If the bean implements
InitializingBean
, itsafterPropertiesSet()
method is called. If it has a custom init-method, that method is called. - Post-initialization: Any
BeanPostProcessor
'spostProcessAfterInitialization()
method is called. - In Use: The bean is ready for use.
- Destruction: When the container is shut down, if the bean implements
DisposableBean
, itsdestroy()
method is called. If it has a custom destroy-method, that method is called.
Customizing Lifecycle Callbacks
Spring provides several ways to customize the bean lifecycle. You can use interfaces like
InitializingBean
DisposableBean
@PostConstruct
@PreDestroy
BeanPostProcessor
The default scope for Spring beans is 'singleton'. This means that for any given bean definition, the Spring container will only create one instance and reuse it for all subsequent requests.
Visualizing the Spring Bean Lifecycle: Imagine a factory (the Spring container) that builds objects (beans). First, it creates the raw object (instantiation). Then, it adds necessary parts like wheels and an engine (property population). Before the object is ready, it might undergo a quality check (pre-initialization) and then a final assembly step (initialization). Once ready, it's handed over for use. When the factory closes (container shutdown), any remaining objects are properly dismantled (destruction).
Text-based content
Library pages focus on text content
Choosing the Right Scope
Selecting the appropriate bean scope is crucial for managing state and resources effectively. Singleton is ideal for stateless services or configuration objects. Prototype is useful for stateful objects where each client needs its own independent instance. Request and Session scopes are specific to web applications and help manage state per user interaction or session.
Singleton
Request scope
Lifecycle interfaces (InitializingBean, DisposableBean) and annotations (@PostConstruct, @PreDestroy).
Learning Resources
The official Spring Framework documentation provides a comprehensive overview of all available bean scopes and their behavior.
Detailed explanation of the bean lifecycle, including various callback interfaces and their order of execution.
Specific guidance on using request, session, and other web-aware scopes within a Spring Boot application.
A practical and easy-to-understand guide to Spring bean scopes with code examples.
An in-depth tutorial covering the various stages of a Spring bean's lifecycle and how to customize them.
A clear explanation of bean scopes and lifecycles in the context of Spring Boot, with illustrative examples.
A video tutorial that visually explains the different stages of a Spring bean's lifecycle.
A video that breaks down the concept of Spring bean scopes and when to use each one.
Learn how to use the `@PostConstruct` and `@PreDestroy` annotations for simpler lifecycle management in Spring.
A tutorial on using the `BeanPostProcessor` interface for advanced customization of bean initialization and destruction.