Sobes.tech
Middle

What scopes in Spring do you know?

sobes.tech AI

Answer from AI

In Spring Framework, the following bean scopes (areas of visibility) are standard:

  • singleton: One instance of the bean is created for each Spring container context. This is the default scope.
  • prototype: A new instance is created each time the bean is requested.
  • request: A bean instance is created for each HTTP request. Only valid in a web context.
  • session: A bean instance is created for each HTTP session. Only valid in a web context.
  • application: A bean instance is created for the entire lifecycle of the ServletContext. Only valid in a web context.
  • websocket: (since Spring 4.0) A bean instance is created for each WebSocket session lifecycle.

Example of declaring a bean with a specific scope:

@Component
@Scope("prototype") // Or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class MyPrototypeBean {
    // ...
}

For web scopes (request, session, application), annotations like @RequestScope, @SessionScope, @ApplicationScope are typically used.

What scopes in Spring do you know? — Java - sobes.tech