LibraryBean Scopes and Lifecycles

Bean Scopes and Lifecycles

Learn about Bean Scopes and Lifecycles as part of Java Enterprise Development and Spring Boot

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 NameDescriptionLifecycle
SingletonA 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.
PrototypeA 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.
RequestA 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.
SessionA 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.
ApplicationA 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:

  1. Instantiation: The bean is created by the container.
  2. Population of Properties: The container injects dependencies (e.g., via setters or constructor arguments).
  3. BeanNameAware: If the bean implements BeanNameAware, its setBeanName() method is called.
  4. BeanFactoryAware: If the bean implements BeanFactoryAware, its setBeanFactory() method is called.
  5. ApplicationContextAware: If the bean implements ApplicationContextAware, its setApplicationContext() method is called.
  6. Pre-initialization: Any BeanPostProcessor's postProcessBeforeInitialization() method is called.
  7. Initialization: If the bean implements InitializingBean, its afterPropertiesSet() method is called. If it has a custom init-method, that method is called.
  8. Post-initialization: Any BeanPostProcessor's postProcessAfterInitialization() method is called.
  9. In Use: The bean is ready for use.
  10. Destruction: When the container is shut down, if the bean implements DisposableBean, its destroy() 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

code
InitializingBean
and
code
DisposableBean
, or annotations like
code
@PostConstruct
and
code
@PreDestroy
for simpler initialization and destruction logic. For more complex scenarios,
code
BeanPostProcessor
offers powerful interception capabilities.

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.

What is the default scope for Spring beans?

Singleton

Which scope creates a new bean instance for every HTTP request?

Request scope

What are the two primary ways to define custom initialization and destruction callbacks?

Lifecycle interfaces (InitializingBean, DisposableBean) and annotations (@PostConstruct, @PreDestroy).

Learning Resources

Spring Framework Documentation: Scopes(documentation)

The official Spring Framework documentation provides a comprehensive overview of all available bean scopes and their behavior.

Spring Framework Documentation: Bean Lifecycle(documentation)

Detailed explanation of the bean lifecycle, including various callback interfaces and their order of execution.

Spring Boot Documentation: Web Scopes(documentation)

Specific guidance on using request, session, and other web-aware scopes within a Spring Boot application.

Baeldung: Spring Bean Scopes(blog)

A practical and easy-to-understand guide to Spring bean scopes with code examples.

Baeldung: Spring Bean Lifecycle(blog)

An in-depth tutorial covering the various stages of a Spring bean's lifecycle and how to customize them.

Spring Boot Tutorial: Bean Lifecycle and Scopes(blog)

A clear explanation of bean scopes and lifecycles in the context of Spring Boot, with illustrative examples.

Understanding Spring Bean Lifecycle - YouTube(video)

A video tutorial that visually explains the different stages of a Spring bean's lifecycle.

Spring Bean Scopes Explained - YouTube(video)

A video that breaks down the concept of Spring bean scopes and when to use each one.

Spring Framework @PostConstruct and @PreDestroy Annotations(blog)

Learn how to use the `@PostConstruct` and `@PreDestroy` annotations for simpler lifecycle management in Spring.

Spring BeanPostProcessor Tutorial(tutorial)

A tutorial on using the `BeanPostProcessor` interface for advanced customization of bean initialization and destruction.