How we can set the spring bean scope. And what supported scopes does it have?
In Spring, the scope of a bean defines the lifecycle and visibility of that bean within the application context. You can set the scope of a Spring bean using the @Scope
annotation or by defining it in the XML configuration.
Using Annotations:
You can use the @Scope
annotation along with the @Component
, @Service
, @Repository
, or @Controller
annotations to define the scope of a bean.
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("singleton") // Default scope
public class MyBean {
// Bean implementation
}
Common scopes include:
singleton
: A single instance of the bean is created and shared across the application context.prototype
: A new instance of the bean is created each time it is requested.Using XML Configuration:
If you are using XML configuration, you can set the scope in the <bean>
tag.
<bean id="myBean" class="com.example.MyBean" scope="singleton"/>
Spring supports several scopes, which can vary depending on whether you are using Spring's web context or a standard application context:
Singleton:
singleton
Prototype:
prototype
Request (Web context only):
request
Session (Web context only):
session
Global Session (Web context only):
globalSession
Application (Spring 5.0 and later):
application
Here’s an example of how to define different scopes using annotations:
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("singleton")
public class SingletonBean {
// Singleton bean implementation
}
@Component
@Scope("prototype")
public class PrototypeBean {
// Prototype bean implementation
}
@Component
@Scope("request")
public class RequestScopedBean {
// Request-scoped bean implementation
}
@Component
@Scope("session")
public class SessionScopedBean {
// Session-scoped bean implementation
}
Setting the scope of a Spring bean is essential for managing its lifecycle and ensuring that it behaves as expected in your application. Depending on your application's requirements, you can choose the appropriate scope from the supported options.