Sobes.tech
Junior — Middle

Explain what a scope bean is in the Spring container and how the application scope differs from other bean lifecycle scopes.

sobes.tech AI

Answer from AI

In Spring, scope of a bean defines the visibility and lifecycle of the bean instance within the container. The main scopes are:

  • singleton (default) — one instance for the entire Spring container.
  • prototype — a new instance each time it is requested.
  • request — one instance per HTTP request (for web applications).
  • session — one instance per HTTP session.
  • application — one instance per ServletContext (web application).
  • websocket — one instance per WebSocket session.

The application scope differs in that the bean lives within the entire web application and is accessible to all sessions and requests, meaning it is scoped at the ServletContext level. Unlike request or session scopes, where the bean is recreated for each request or session, the application scope guarantees a single instance for the entire lifetime of the application within the servlet container.

Example of declaring a bean with application scope:

@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyAppBean {
    // ...
}

Thus, the application scope is useful for storing data or services that should be shared across the entire web application.