Card 02/ 07
Bean Scopes Example: A Prototype Gives a New Instance Each Time
Two calls to getBean, two different objects, where a singleton would return the same one twice.
Declaring a bean with @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) makes it a prototype, so every request for it produces a new object. Asking for the same prototype twice and comparing the two references shows it.
ReceiptBuilder is declared in a @Bean method with prototype scope instead of the default:
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
ReceiptBuilder receiptBuilder() { return new ReceiptBuilder(); }The context is asked for it twice, and == checks whether the two references point at the same object:
ReceiptBuilder a = context.getBean(ReceiptBuilder.class);
ReceiptBuilder b = context.getBean(ReceiptBuilder.class);
System.out.println("same instance: " + (a == b));same instance: falseThe answer is false: two separate objects. The same comparison on a singleton, the default scope with one shared instance, such as a class marked @Component with no scope, prints true.
So every getBean call, and every injection into another bean, gets its own prototype. That is the trade prototype scope makes: nothing is shared, and the container gives no further help once the object is handed over. It suits objects like ReceiptBuilder that collect data for one use.
← → move through sections and cards