Sobes.tech
Middle

What are the scopes of beans in Spring?

sobes.tech AI

Answer from AI

In the Spring Framework, there are several standard bean scopes:

  • singleton
  • prototype
  • request
  • session
  • application
  • websocket
Scope Description
singleton One instance of the bean per Spring context. Default.
prototype A new bean instance is created for each request.
request One bean instance per HTTP request.
session One bean instance per HTTP session.
application One bean instance per ServletContext. Used by web applications.
websocket One bean instance per WebSocket session.

The request, session, application, and websocket scopes are relevant in a web context (e.g., when using Spring MVC).

You can specify the scope using the @Scope annotation:

// Example singleton
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton") // Explicitly specified, though this is the default
public class SingletonBean {
    // ...
}
// Example prototype
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class PrototypeBean {
    // ...
}
What are the scopes of beans in Spring? — Java - sobes.tech