liveBook · Manning

Prototype scope

As explained in Spring Start Here, Second Edition

Prototype scope is a Spring bean scope in which the container creates a new instance each time the bean is requested.

A prototype bean gives you a new object instance each time you request it from Spring. Unlike a singleton, Spring associates the bean name with its type rather than reusing one stored instance. section 5.2 section 5.4

Figure 5.6 We use the @Scope annotation to change the bean scope in prototype. The bean is now represented as a coffee plant because you get a new object instance each time you refer to it. For this reason, variables cs1 and cs2 will always contain different references, so the output of the code is always “false.”

Think of each request as getting a fresh coffee plant: two lookups return different object references. section 5.2

Declare prototype scope explicitly, and choose it when a mutable object needs Spring capabilities such as dependency injection.

  • For a @Bean method, add @Scope(BeanDefinition.SCOPE_PROTOTYPE); for a class, put @Scope alongside a stereotype such as @Component. section 5.2
  • A mutable CommentProcessor that uses a CommentRepository can be a prototype bean; request it from the application context when needed. section 5.2.1
  • Avoid injecting a prototype directly into a singleton when you need a fresh instance per use: Spring injects it only once as the singleton is created. section 5.4

Check for a fresh instance

Request CommentService twice from the context and compare the references with ==. For a prototype bean, the comparison is false. section 5.2

How Spring Start Here, Second Edition covers it

How deep it goes
Explains lookup-time creation, annotation-based declarations, identity checks, mutable-bean use cases, and singleton-injection caveats.
Examples
Uses repeated CommentService lookups and a mutable CommentProcessor that depends on CommentRepository.
What you can do after
Apply prototype scope with Spring’s @Scope annotation and request fresh instances from the application context.
How it connects
Connects prototype scope to singleton scope, Spring beans, dependency injection, and the application context.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.