Sobes.tech
Middle

What are scope beans used for in Spring?

sobes.tech AI

Answer from AI

Scope bean in Spring defines the lifecycle of a bean and its scope. It manages how bean instances are created, used, and destroyed within the application context.

Main standard scopes:

  • singleton: One bean instance per IoC container. This is the default scope.
  • prototype: A new bean instance is created each time it is requested.
  • request: One bean instance per HTTP request. Relevant for web applications.
  • session: One bean instance per HTTP session. Relevant for web applications.
  • application: One bean instance per ServletContext. Relevant for web applications.

Example of scope configuration:

Using @Scope annotation:

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

Using XML configuration:

<bean id="mySingletonBean" class="com.example.MySingletonBean" scope="singleton"/>
<bean id="myPrototypeBean" class="com.example.MyPrototypeBean" scope="prototype"/>

The choice of scope depends on the application's needs and the nature of the bean itself. Singleton is suitable for stateless services, while prototype is used for stateful beans that may change depending on the context of use. Request, session, and application scopes are used in web applications to manage state at the request, session, or application level respectively.