java / beginner
Snippet
Managing Bean Creation Scopes with Scope Annotation
By default, Spring beans are singletons, meaning one shared instance exists per container. Annotating a class with @Scope(SCOPE_PROTOTYPE) applies the Prototype pattern, instructing Spring to create a brand new, independent object instance every time the bean is requested or injected.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)public class ShoppingCart {private final List<String> items = new ArrayList<>();public void addItem(String item) {this.items.add(item);}public int getItemCount() {return this.items.size();}}
spring
Breakdown
1
@Component
Registers the ShoppingCart class as a Spring-managed bean candidate.
2
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Changes the bean lifecycle from singleton (default) to prototype (new instance per injection/request).
3
private final List<String> items = new ArrayList<>();
Maintains state private to each distinct prototype bean instance.
4
public void addItem(String item) {
Mutates the internal item list without affecting other ShoppingCart instances.