Hello! In our last lesson, we explored the different ways Spring performs dependency injection, concluding that constructor injection is the modern standard for building robust and testable applications. We now know that the Spring container creates beans and wires them together. But what happens after that?
This lesson dives into the lifespan of a Spring bean. We will investigate how its scope determines how many instances are created and for how long they exist. We'll also examine lifecycle callbacks, which allow you to execute custom logic at critical moments—right after creation and just before destruction. Understanding these concepts is essential for managing resources, handling state, and correctly predicting your application's behavior. As this is a fundamental part of the Spring framework, you can be sure it will be a key topic in your technical interviews.
What is a Bean's Scope?
A bean's scope defines the strategy the Spring container uses to create and manage instances of that bean. It answers the questions: How many instances of this bean should exist? And what is their lifetime?
Spring offers several scopes, but you will primarily work with two foundational ones: singleton and prototype. The others are specific to web applications.
This visual provides a great at-a-glance summary of the main scopes.

Let's explore these in more detail. The following resource provides excellent explanations of each scope.
Spring Beans Explained: Configuration, IoC Container ...
This article by Kamil Mazurek provides clear, detailed descriptions of each bean scope with code examples.
Please read the section on Spring Bean Scopes. Focus on understanding the distinct behavior of: Singleton (the default): One shared instance for the entire application. Prototype: A new instance is created every time the bean is requested. Request, Session, Application: Briefly review these web-aware scopes to understand their purpose in the context of HTTP requests and user sessions.
To summarize the key points:
- Singleton: This is the default scope. Only one instance of the bean is created per Spring IoC container. Every time any other component asks for this bean, it gets the exact same object. This is ideal for stateless components like services, repositories, and configuration classes.
- Prototype: A new instance is created every single time the bean is requested from the container. This is suitable for stateful objects, where each client needs its own distinct copy to work with, for example, a builder object for creating a complex report.
- Web Scopes:
- Request: A new instance for each HTTP request.
- Session: A new instance for each user's HTTP session.
- Application: A single instance for the entire web application's
ServletContext.
The Singleton-Prototype Dependency Trap: An Interview Favorite
A classic interview question explores what happens when you inject a prototype-scoped bean into a singleton-scoped bean. Since you have experience building services (@Service, a singleton by default), this is a practical scenario.
Imagine your singleton OrderService needs a prototype ShoppingCart bean.
@Service // Singleton scope by default
public class OrderService {
private final ShoppingCart cart;
// Dependencies are injected only ONCE when the singleton is created
public OrderService(ShoppingCart cart) {
this.cart = cart;
}
public void processOrder() {
// ... uses the 'cart' instance
}
}
@Component
@Scope("prototype")
public class ShoppingCart {
// ... stateful logic
}
You might expect that each call to processOrder() would get a fresh ShoppingCart. However, that's not what happens. The dependency injection occurs only once, when the OrderService singleton is first created. The OrderService will hold a reference to that single ShoppingCart instance for its entire lifetime, effectively treating it like a singleton.
The following video discusses this exact problem and the solution.
The Ultimate Guide to Understanding Spring Bean Scopes #spring #beans #java #scope
The "Lazy Programmer" channel gives a concise explanation of bean scopes. The section on singleton/prototype interaction is particularly relevant.
Watch the segment from Singleton beans with prototype dependencies. The video explains why direct injection doesn't work as expected and introduces the concept of method injection as a solution. Spring provides the @Lookup annotation for this purpose, as noted in the "Interview Tip" from the image we saw earlier.
The Bean Lifecycle: Birth, Life, and Death
Beyond its scope, every bean follows a distinct lifecycle within the Spring container. The container doesn't just create an object; it orchestrates a series of steps from instantiation to destruction. Understanding these steps allows you to hook in your own custom logic at precise moments.
This diagram shows the major phases of a bean's life.

We can group the lifecycle into four main stages:
- Instantiation: Spring creates an instance of the bean, typically by calling its constructor.
- Populate Properties: Spring resolves and injects dependencies (as we saw in the previous lesson).
- Initialization: Spring calls special callback methods to allow the bean to perform any setup tasks (e.g., populating a cache, connecting to a resource).
- Destruction: Just before the container shuts down and removes the bean, it calls destruction callbacks to allow for cleanup (e.g., closing a file handle, shutting down a connection pool).
Initialization and Destruction Callbacks
For a developer, the most important parts of the lifecycle to interact with are initialization and destruction. Spring provides three primary mechanisms for this, which are a frequent subject of interview questions.
The following video is an excellent interview-focused preparation resource that walks through each mechanism with clear code examples.
Spring bean life cycle | Bean Initialization & Destroy Callbacks | Spring boot interview prep #1
This video from "Selenium Express" is framed as interview prep and covers the exact concepts for this part of our lesson: initialization and destruction callbacks.
Please watch the following segments: @PostConstruct: Watch from this first segment to see the modern, recommended way to define an initialization method. InitializingBean: Next, watch this explanation of the Spring-specific interface alternative. Order of Execution: The presenter then tests what happens when both are present. Watch this crucial part from the execution order test. @Bean(initMethod): Finally, see how to specify an init method in a configuration class from this clip.
After watching, let's turn our attention to the destruction phase.
Spring bean life cycle | Bean Initialization & Destroy Callbacks | Spring boot interview prep #1
We'll continue with the same video.
Now, watch these segments about bean destruction: @PreDestroy and Container Shutdown: Watch the introduction to destruction from this point. Then, pay close attention to the explanation of how the container is shut down from container shutdown mechanisms. This is key to understanding when destruction callbacks are triggered. DisposableBean: See the interface-based alternative from this clip. Standalone vs. Web App: The video ends with a vital distinction. Watch from this final part to understand who is responsible for closing the container.
To solidify this knowledge, the following article provides a textual reference detailing the precise order of execution when you combine multiple callback mechanisms.
Spring bean Lifecycle Callbacks - JSR 250 | Jstobigdata
This article from Jstobigdata provides a clear summary of the callback execution order.
Please read the section titled Combining all mechanisms. This explicitly states the order for both initialization and destruction, which is a common interview question.
Here is a summary of the callback mechanisms and their execution order:
| Phase | Callback Order | Method | Type | Recommendation |
|---|---|---|---|---|
| Initialization | 1 | @PostConstruct |
JSR-250 Annotation | Recommended. Modern, clean, and not coupled to Spring. |
| 2 | afterPropertiesSet() |
InitializingBean Interface |
Avoid. Tightly couples your code to the Spring framework. | |
| 3 | initMethod |
@Bean attribute / XML |
Useful for third-party or legacy code you cannot annotate. | |
| Destruction | 1 | @PreDestroy |
JSR-250 Annotation | Recommended. The counterpart to @PostConstruct. |
| 2 | destroy() |
DisposableBean Interface |
Avoid. Tightly couples your code to Spring. | |
| 3 | destroyMethod |
@Bean attribute / XML |
Useful for third-party or legacy code. |
An important note on prototype beans: The Spring container does not manage the complete lifecycle of prototype beans. It creates, configures, and initializes them, but then hands them over to the client. The container does not keep a reference to them, and therefore destruction callbacks like @PreDestroy or DisposableBean.destroy() are NOT called. You, the developer, are responsible for cleaning up any resources held by prototype-scoped beans.
Conclusion
In this lesson, we've gone deep into the life and death of a Spring bean. By combining your knowledge of dependency injection with bean scopes and lifecycle callbacks, you can now predict not just how your application components are wired, but also how they behave throughout their lifetime. This is a level of understanding that separates a junior developer from an experienced one and is critical for passing technical interviews.
Key Takeaways:
- Bean Scopes:
singleton(the default) creates one shared instance, whileprototypecreates a new instance for every request. Web scopes (request,session,application) are tied to the lifecycle of web interactions. - Singleton/Prototype Injection: Injecting a prototype bean into a singleton results in the singleton holding a single instance of that prototype. Use
@Lookupfor cases where a singleton needs fresh prototype instances at runtime. - Lifecycle Callbacks: Use
@PostConstructfor initialization logic and@PreDestroyfor cleanup logic. They are the modern standard because they decouple your business logic from the Spring framework. - Callback Order: Spring executes callbacks in a strict order:
@PostConstruct->InitializingBean->init-method. For destruction, the order is@PreDestroy->DisposableBean->destroy-method. - Prototype Destruction: Spring does not manage the destruction of prototype beans. Destruction callbacks are not invoked for them.
In our next lesson, we will tackle another crucial aspect of Spring's inner workings: auto-configuration. We'll learn how to use Spring Boot's condition evaluation report to understand exactly why a particular bean was—or was not—created, giving you powerful debugging capabilities.