Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

What are the different scope of Beans in Spring?

Different Scopes of Beans in Spring:


1: Singleton

Only one instance of the bean is created for the entire Spring container. (Default scope)

@Scope("singleton")
//Only one bean instance for the entire Spring container.


2: Prototype

A new instance is created every time the bean is requested.

@Scope("prototype")
//A new bean instance each time it is requested.


3: Request

A new bean is created for each HTTP request. (Used in web applications)

@Scope("request")
//A new bean instance for every HTTP request (web apps).


4: Session

A new bean is created for each HTTP session. (Used in web applications)

@Scope("session")
//A new bean instance for every HTTP session (web apps).


5: Application

One bean is created for the entire web application.

@Scope("application")
//One bean instance for the entire web application.


6: Websocket

One bean is created for each WebSocket connection.

@Scope("websocket")
//A new bean instance for every WebSocket connection.


Example usage in code:

@Component
@Scope("singleton") // Use "prototype", "request", etc. as needed
public class MyBean { }


Tip to remember:

- Singleton = One for all

- Prototype = One per request

- Request/Session/Application/Websocket = Used in web apps, based on the lifecycle (request, session, app, or websocket)

Ready for commit