Chapter 5: The Spring context: Bean scopes and life cycle
Introduces bean scopes as Spring’s approaches to creating and managing beans, identifying singleton as the default and prototype as another common scope.
After this chapter you will be able to
- Bean scopes and defaults. Explain that a bean scope describes an approach Spring uses to create beans and manage their life cycle. State that singleton is the default scope and prototype is another common scope.
- Singleton Identity Per Bean Name. Explain that singleton is Spring’s default bean scope: the context returns the same instance for a particular bean name, though it can contain multiple beans of the same type under different names.
- Shared Stereotype Bean Injection. Explain that singleton behavior is the same for beans declared with stereotype annotations: when CommentService and UserService depend on CommentRepository, Spring injects the same repository reference into both.
- Immutable singleton design. Explain why singleton beans should be immutable in multithreaded apps and why synchronizing a mutable singleton is usually a poor alternative.
- Bean and scope selection. State when an object should be a Spring bean and how immutability affects the choice between singleton and prototype scope.
- Singleton bean creation timing. Distinguish when Spring creates singleton beans with eager versus lazy instantiation.
- Eager versus lazy tradeoffs. Justify the section’s preference for eager instantiation while explaining when lazy instantiation may help.
- Prototype bean instance creation. Explain that Spring creates a new object instance each time a prototype-scoped bean is requested, rather than maintaining one instance for that bean.
- Distinct injected repository instances. Describe what happens when two service beans each receive an @Autowired prototype CommentRepository.
- Bean candidacy and dependency injection. Explain why CommentProcessor does not initially need to be a bean, but does when it needs Spring to inject CommentRepository.
- Mutable processor scope choice. Justify choosing prototype rather than singleton scope for the mutable CommentProcessor in the concurrent-use scenario.
- Per-call prototype retrieval. Describe how CommentService obtains a new CommentProcessor for each sendComment() call and why directly injecting the processor would not do that.
What it builds on
- Using the @Bean annotation to create beans (chapter 2) · Assumes familiarity with adding beans to the Spring context.
- Using stereotype annotations to create beans (chapter 2) · Assumes familiarity with defining beans using stereotype annotations.
- Using @Autowired to inject the values through the class fields (chapter 3) · Assumes familiarity with @Autowired field injection.
- Using @Autowired to inject the values through the constructor (chapter 3) · Injecting dependencies through a constructor.
- Deciding which objects should be part of the Spring context (chapter 4) · Deciding which objects belong in the Spring context.
- Using the @Autowired annotation to inject beans (chapter 3) · Introduces injecting beans with @Autowired.
Section by section
Introduction
Introduces bean scopes as Spring’s approaches to creating and managing beans, identifying singleton as the default and prototype as another common scope.
- Bean scopes and defaults: Explain that a bean scope describes an approach Spring uses to create beans and manage their life cycle. State that singleton is the default scope and prototype is another common scope.
Why it matters: Scopes give you a way to think about bean creation beyond Spring’s default behavior.
Key terms: bean, scope, life cycle, singleton, prototype
5.1 Using the singleton bean scope
This section explains that Spring’s default singleton scope returns the same bean instance for a given name and shows that behavior with both @Bean and stereotype annotations.
- Singleton Identity Per Bean Name: Explain that singleton is Spring’s default bean scope: the context returns the same instance for a particular bean name, though it can contain multiple beans of the same type under different names.
Why it matters: This distinction helps you predict whether two references point to the same object. - Named Bean Reference Test: Describe how the @Bean example demonstrates singleton behavior: the annotated method supplies the bean name, and retrieving that bean twice gives references that compare equal with ==. Explain that lookup by type also works when it is the only bean of that kind.
Why it matters: The reference comparison makes the singleton guarantee observable rather than just a definition. - Shared Stereotype Bean Injection: Explain that singleton behavior is the same for beans declared with stereotype annotations: when CommentService and UserService depend on CommentRepository, Spring injects the same repository reference into both.
Why it matters: It shows that singleton sharing applies to injected dependencies, not just beans retrieved directly from the context.
Key terms: singleton bean scope, bean name, bean ID, Spring context, @Bean, object reference, ==, stereotype annotations, @Autowired, CommentService
5.1.1 Singleton beans in real-world scenarios
This section explains why shared singleton beans should be immutable and how to choose whether an object should be a bean and which scope suits it.
- Immutable singleton design: Explain why singleton beans should be immutable in multithreaded apps and why synchronizing a mutable singleton is usually a poor alternative.
Why it matters: It helps you avoid unexpected results when several threads use the same bean. - Constructor injection and immutable fields: Describe how constructor injection helps make a bean immutable in the section’s CommentService example.
Why it matters: It gives you a concrete way to design a singleton whose dependencies do not change. - Bean and scope selection: State when an object should be a Spring bean and how immutability affects the choice between singleton and prototype scope.
Why it matters: It keeps Spring management purposeful and helps you avoid choosing a shared scope for mutable state.
Key terms: singleton bean scope, immutable, race condition, thread synchronization, constructor injection, field injection, final, CommentService, Spring context, bean
5.1.2 Using eager and lazy instantiation
This section contrasts when Spring creates eager and lazy singleton beans, demonstrates the difference, and explains when each choice is useful.
- Singleton bean creation timing: Distinguish when Spring creates singleton beans with eager versus lazy instantiation.
Why it matters: Creation timing determines whether an unused singleton exists as soon as the context starts. - Lazy configuration and observation: Describe how the CommentService example configures lazy instantiation and uses constructor output to show whether the bean was created.
Why it matters: The constructor message makes the effect of @Lazy visible without relying on a bean’s business behavior. - Eager versus lazy tradeoffs: Justify the section’s preference for eager instantiation while explaining when lazy instantiation may help.
Why it matters: Choosing a creation strategy affects startup cost, memory use, and when bean-creation problems become visible.
Key terms: singleton beans, eager instantiation, lazy instantiation, Spring context, @Lazy, @Bean, stereotype annotation, CommentService, constructor, startup
5.2 Using the prototype bean scope
This section explains how prototype scope creates distinct bean instances, how to declare it, and what happens when beans are requested or injected.
- Prototype bean instance creation: Explain that Spring creates a new object instance each time a prototype-scoped bean is requested, rather than maintaining one instance for that bean.
Why it matters: This is the behavior that distinguishes prototype scope from reusing a single bean instance. - Prototype scope declaration placement: Describe where to put @Scope to declare a prototype bean with either a @Bean method or a stereotype-annotated class.
Why it matters: The annotation must be placed on the declaration Spring uses to create the bean. - Separate instances across threads: Explain why separate prototype instances avoid the shared-instance concurrency problem described for mutable beans.
Why it matters: Separate instances explain why the section treats mutable prototype beans differently from shared singleton beans. - Distinct injected repository instances: Describe what happens when two service beans each receive an @Autowired prototype CommentRepository.
Why it matters: Prototype scope affects objects supplied through dependency injection as well as objects requested directly from the context.
Key terms: prototype-scoped bean, getBean(), instance, @Scope, @Bean, stereotype annotations, prototype beans, mutable prototype beans, concurrency problems, CommentRepository
5.2.1 Prototype beans in real-world scenarios
The section explains when a mutable object should become a prototype bean and how to obtain a fresh instance for each service call.
- Bean candidacy and dependency injection: Explain why CommentProcessor does not initially need to be a bean, but does when it needs Spring to inject CommentRepository.
Why it matters: Not every object needs to be managed by Spring, even in a Spring application. - Mutable processor scope choice: Justify choosing prototype rather than singleton scope for the mutable CommentProcessor in the concurrent-use scenario.
Why it matters: The bean’s scope must fit how its mutable state is used. - Per-call prototype retrieval: Describe how CommentService obtains a new CommentProcessor for each sendComment() call and why directly injecting the processor would not do that.
Why it matters: A prototype declaration alone does not give every call of a singleton service a fresh processor. - Legacy refactoring tradeoff: Explain why the author might use prototype beans when refactoring an older application despite generally avoiding mutable instances.
Why it matters: The example presents prototype scope as a practical compromise, not a default design choice.
Key terms: bean, Spring context, DI, CommentProcessor, CommentRepository, prototype, singleton, mutable, race conditions, CommentService
5.3 Questions
This section lists review questions about bean scopes and instantiation but does not explain their answers.
5.4 Summary
Summarizes how singleton and prototype scopes affect bean creation, sharing, thread safety, and injection.
Where this is used later
- (chapter intro) (chapter 9) · Introduces prototype as an application bean scope.
Concepts explained in this chapter
- singleton scopeA singleton bean is a Spring bean for which the container maintains one shared instance within its context.
- prototype scopePrototype scope is a Spring bean scope in which the container creates a new instance each time the bean is requested.
- race conditionA race condition is an incorrect or nondeterministic result caused by concurrent operations accessing shared state without adequate coordination.
- eager instantiationEager instantiation is the creation of an object or bean before it is explicitly requested, typically during container initialization.
- lazy initializationLazy instantiation is the creation of an object or bean only when it is first requested or otherwise needed.
- @lazy annotationThe @Lazy annotation is a Spring annotation that configures a bean for lazy instantiation.
- immutabilityImmutability is the property that an object's state cannot be changed after initialization.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
