Card 02/ 07

ExampleDifficulty: Intermediate1 min

Prototype Scope: a Fresh Instance Every Time

ReceiptBuilder is declared prototype scope instead of the default. Two calls to getBean on it behave nothing like the same call on a singleton.

java
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
ReceiptBuilder receiptBuilder() { return new ReceiptBuilder(); }
java
ReceiptBuilder a = context.getBean(ReceiptBuilder.class);
ReceiptBuilder b = context.getBean(ReceiptBuilder.class);
System.out.println("same instance: " + (a == b));
text
same instance: false
run in a container — contrast with the @Component demo two topics back, which printed true

Every getBean call on a prototype produces a new object. That is the whole trade prototype scope makes: no sharing, and — as the next card shows — no help from the container once it's handed over, either.