Sobes.tech
Middle

What scope areas do you know in Spring?

sobes.tech AI

Answer from AI

Spring supports several bean scopes:

  • singleton: Shares a single bean definition instance per Spring container. This is the default scope.
  • prototype: Creates a new bean instance each time it is requested.
  • request: Shares a single bean definition instance within the lifecycle of an HTTP request. Only applicable in a web application context.
  • session: Shares a single bean definition instance within the lifecycle of an HTTP session. Only applicable in a web application context.
  • application: Shares a single bean definition instance within the lifecycle of a ServletContext. Only applicable in a web application context.
  • websocket: Shares a single bean definition instance within the lifecycle of a WebSocket connection. Only applicable in a web application context.

To declare a scope, you can use the @Scope annotation:

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

Or in XML configuration:

<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

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

</beans>

It is important to note that the request, session, application, and websocket scopes are only available when using WebApplicationContext.