In this tutorial, you will learn what @Scope annotation is and how to use it in Spring.
@Scope is a Spring annotation used to specify a bean’s lifecycle. It can be used to define the lifecycle of a bean as a singleton, prototype, request, session, or global session.
If you are interested to learn about other Spring Boot annotations as well, check out the following tutorials:
How to User @Scope Annotation
In Spring Boot, the default scope of a bean is a singleton, which means that only one instance of the bean is created for the entire application. The @Scope annotation allows you to override the default behaviour and specify a different lifecycle for the bean.
Here’s an example of how to use the @Scope annotation in a Spring Boot application:
@Service @Scope("prototype") public class MyService { // service code goes here }
In this example, the MyService class is annotated with the @Scope("prototype")
annotation, which means that a new instance of the bean will be created every time it is requested.
Scopes
Below is a list of different scopes that you can use with the @Scope annotation:
- singleton: Only one instance of the bean is created for the entire application. This is the default scope.
- prototype: A new instance of the bean is created every time it is requested.
- request: A new instance of the bean is created for each HTTP request.
- session: A new instance of the bean is created for each HTTP session.
- global session: A new instance of the bean is created for each global HTTP session.
You can use the @Scope annotation in your Spring Boot application to specify the lifecycle of a bean and control how it is created and managed by the Spring container.
I hope this tutorial was helpful to you. If you are interested to learn more, check out other Spring Boot tutorials for beginners.
Happy learning!