How to Define the Scope of a Bean?
Defining the scope of a bean is an important aspect of managing the lifecycle and visibility of beans in a dependency injection framework, such as Spring. The scope determines how long a bean will live and how it will be shared within the application. Here are the common scopes available in Spring and how to define them:
Singleton (default scope):
@Bean
@Scope("singleton")
public MyBean myBean() {
return new MyBean();
}
Prototype:
@Bean
@Scope("prototype")
public MyBean myBean() {
return new MyBean();
}
Request (web-aware scope):
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public MyBean myBean() {
return new MyBean();
}
Session (web-aware scope):
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public MyBean myBean() {
return new MyBean();
}
Global Session (web-aware scope):
@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION)
public MyBean myBean() {
return new MyBean();
}
Using Annotations:
@Scope
annotation in combination with the @Component
, @Service
, @Repository
, or @Controller
annotations.@Component
@Scope("prototype")
public class MyPrototypeBean {
// Bean implementation
}
Using XML Configuration:
<bean id="myBean" class="com.example.MyBean" scope="prototype"/>
Programmatic Configuration:
ConfigurableBeanFactory
interface.@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
@Bean
public void configureBeanFactory(ConfigurableBeanFactory factory) {
factory.registerScope("prototype", new PrototypeScope());
}
}
Defining the scope of a bean is crucial for managing its lifecycle and ensuring that it behaves as expected in your application. Choose the appropriate scope based on your application's requirements, and use the appropriate method (annotations, XML, or programmatic configuration) to define it.