Loading

Quipoin Menu

Learn • Practice • Grow

spring / Spring Bean Scopes
tutorial

Spring Bean Scopes

Imagine you have a coffee machine at work. If you want a fresh cup every time, you get a new cup (Prototype). But the machine itself is a single shared appliance for everyone (Singleton).
Bean scopes define how many instances of a bean Spring creates and how long they live.

Spring provides several scopes:

  • singleton (default): Only one instance per Spring container. Shared across the entire application.
  • prototype: A new instance every time the bean is requested.
  • request: One instance per HTTP request (only in web-aware contexts).
  • session: One instance per HTTP session.
  • application: One instance per ServletContext.
  • websocket: One instance per WebSocket.

You can specify scope using @Scope annotation or scope attribute in XML.


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class MyPrototypeBean {
public MyPrototypeBean() {
System.out.println("Prototype bean created");
}
}
<bean id="myPrototypeBean" class="MyPrototypeBean" scope="prototype"/>
Two Minute Drill
  • Bean scope determines the number and lifetime of bean instances.
  • singleton: one instance per container (default).
  • prototype: new instance on each request.
  • Web scopes (request, session) are available in web applications.
  • Use @Scope to change scope.

Need more clarification?

Drop us an email at career@quipoinfotech.com