Understanding Spring Bean Scopes: When Singleton Becomes Prototype
This article explains how Spring manages bean instances, compares singleton and prototype scopes with concrete code examples, and shows why two injected beans may be equal or different depending on the @Scope annotation applied to the component class.
Singleton bean behavior
By default Spring creates a single instance of each bean (singleton scope) and stores it in the container cache. All dependency injections for that bean reference the same object, so in the example the coach and anotherCoach fields point to the identical bean instance and the comparison prints true.
Bean scopes in Spring
singleton : one shared instance per container (default).
prototype : a new instance is created each time the bean is requested.
request : one instance per HTTP request (web applications only).
session : one instance per HTTP session (web applications only).
application : one instance per ServletContext (web applications only).
websocket : one instance per WebSocket session (web applications only).
Changing a bean to prototype
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CricketCoach implements Coach {
// ...
}When the CricketCoach class is annotated with @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE), each injection receives a distinct object. Consequently, the comparison in the constructor prints false because coach and anotherCoach are different instances.
Reverting to singleton
If the scope annotation is switched back to SCOPE_SINGLETON, the two injected beans become identical again, and the comparison result flips to true. This demonstrates how the chosen bean scope directly influences object identity and lifecycle within a Spring application.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
