Sobes.tech
Junior — Middle

Explain the principle of operation and the purpose of the scope in the Spring Framework.

sobes.tech AI

Answer from AI

In the Spring Framework, scope defines the lifecycle and visibility of a bean (component) within the Spring container.

Main scope types:

  • singleton (default): one instance of the bean for the entire Spring container.
  • prototype: a new instance is created each time it is requested.
  • request: the bean lives within the scope of an HTTP request (for web applications).
  • session: the bean lives within the scope of an HTTP session.
  • application: the bean lives within the scope of the ServletContext.

Scope allows controlling how and when objects are created, which is important for resource management and application state.

For example, to create a prototype bean:

@Component
@Scope("prototype")
public class MyBean {
    // ...
}

Thus, each time MyBean is requested from the container, a new instance will be created.