liveBook · Manning

Chapter 5: The Spring context: Bean scopes and life cycle

What you will learn in chapter 5 of Spring Start Here, Second Edition

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

What it builds on

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.

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.

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.

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.

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.

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.

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

Concepts explained in this chapter

← Chapter 4: The Spring context: Using abstractions Chapter 6: Using aspects with Spring AOP →

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.