![]() |
VOOZH | about |
In the Spring Framework, each bean defined in the IoC container has a scope that determines its lifecycle and how many instances are created. By default, Spring creates only one instance of a bean (singleton scope), but it also supports other scopes that control how and when new bean instances are generated.
The @Scope annotation is used to define this behavior at either the class level (for components) or method level (for @Bean methods).
The @Scope annotation defines the lifecycle scope of a bean. By default, every Spring bean is singleton, meaning the same instance is shared across the container.
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {
String value() default "singleton";
}
We’ll create a simple shopping application to demonstrate how singleton and prototype scopes work.
Since we didn’t specify any scope, Spring treats this bean as a singleton.
This is a simple POJO representing a product with basic attributes.
Laptop.java
Mobile.java:
Both classes extend Device and add specific attributes to represent product types.
This configuration file declares Device beans and enables component scanning for @Component classes.
Here, each call to context.getBean(ShoppingList.class) fetches the same bean instance because the default scope is singleton.
Output (Singleton Scope):
All lists share the same instance, showing singleton behavior.
To create a new instance each time, annotate the bean with @Scope("prototype").
Updated ShoppingList.java:
Now, each getBean() call creates a separate instance.
Now if we rerun the Main.java class, we can see the three different shopping lists. The output will be as follows.
Each shopping list is now independent.