How do you define a bean scope?
How do you define a bean scope?
To define a bean scope in Spring, you specify the lifecycle and visibility of a bean within the application contexts it is used. The Spring framework supports several scopes, but the most commonly used are singleton and prototype. Additionally, there are web-aware scopes like request, session, application, and websocket.
Here's how you can define a bean scope:
Annotation-based Configuration: You can use the @Scope annotation on the bean definition to specify its scope. For example, to define a singleton scope (which is the default), you can use @Scope("singleton") or simply omit the scope as singleton is the default. For a prototype scope, you would use @Scope("prototype").
@Component
@Scope("prototype")
public class MyPrototypeBean {
// class body
}
Java-based Configuration: When using Java configuration, you can use the @Bean annotation along with @Scope in a configuration class.
@Configuration
public class AppConfig {
@Bean
@Scope("singleton") // This is optional as singleton is the default scope
public MySingletonBean mySingletonBean() {
return new MySingletonBean();
}
@Bean
@Scope("prototype")
public MyPrototypeBean myPrototypeBean() {
return new MyPrototypeBean();
}
}
XML-based Configuration: In XML conf...
middle