1. Introduction:
In Spring Boot, @Scope
and @Bean
annotations are used to control the lifecycle and scope of a bean in the Spring IoC (Inversion of Control) container.
2. @Bean Annotation:
The @Bean
annotation is used to declare a method as a producer of a bean. This method is responsible for creating and configuring an instance of a bean, and the returned object is managed by the Spring container.
Example:
In this example, the myBean
method annotated with @Bean
is responsible for creating an instance of MyBean
, and this bean is now available in the Spring application context.
3. @Scope Annotation:
The @Scope
annotation is used to define the scope of a bean. The scope determines the lifecycle and visibility of a bean in the Spring container.
![](https://delta-dev-software.fr/wp-content/uploads/2024/01/1_P-mx2iDQg_Pj_M15UgJpqA-1024x563.png)
Commonly used scopes include:
singleton
: A single instance for the entire Spring container (default).prototype
: A new instance for each request.request
: A new instance for each HTTP request (web applications only).session
: A new instance for each HTTP session (web applications only).
Example:
In this example, the myPrototypeBean
method is annotated with @Scope("prototype")
, indicating that a new instance of MyPrototypeBean
should be created for each request.
4. Using Beans with Different Scopes:
Once beans with different scopes are defined, you can inject and use them in other Spring components.
Example:
In this example, MyService
is a Spring service that uses two beans: myBean
with the default singleton scope and myPrototypeBean
with the prototype scope.
5. Conclusion:
Understanding and using @Scope
and @Bean
annotations are crucial for managing the lifecycle and scope of beans in a Spring Boot application. Properly choosing the scope based on your application’s requirements helps control resource usage and ensures the correct behavior of your components.
Refer to the official Spring documentation for more details:
Feel free to explore additional features such as custom scopes, initialization, and destruction methods for beans as you advance in your Spring Boot journey!