Overview

5 The Spring context: Bean scopes and life cycle

In this chapter, the focus shifts from simply defining Spring beans to understanding how Spring creates, stores, and manages them over time. Spring uses bean scopes to control these behaviors, with singleton and prototype being the two main scopes discussed. The chapter emphasizes that scope choice affects not only how many instances exist, but also how those instances are shared, injected, and used across an application.

Singleton is the default Spring scope and means that Spring associates a single instance with a bean name, returning that same instance whenever it is requested by that name. The chapter shows that singleton beans can be created with either configuration methods or stereotype annotations, and that dependency injection will consistently supply the same singleton reference wherever it is needed. It also distinguishes eager instantiation, where singleton beans are created when the context starts, from lazy instantiation, where creation is postponed until the bean is first needed. Eager creation is generally preferred because it simplifies startup behavior, exposes configuration problems early, and avoids extra runtime checks, while lazy creation can help reduce startup cost and memory use in large or partially used applications.

The second major topic is prototype scope, where Spring creates a new instance each time the bean is requested rather than reusing one shared object. This makes prototype beans suitable for mutable state, especially when different threads or operations need separate instances to avoid race conditions. The chapter also explains that prototype beans must be explicitly declared and that injecting a prototype bean directly into a singleton can be misleading, because the singleton receives only one instance at creation time. A practical pattern is to request the prototype from the application context when needed, allowing each use to get a fresh object. Overall, the chapter advises using Spring beans only when the framework needs to manage the object, preferring immutable singleton beans by default, and reserving prototype scope for cases where mutable, per-use instances are truly necessary.

When one refers to a singleton class in an app, they mean a class that offers only one instance to the app and manages the creation of that instance. In Spring, however, singleton doesn’t mean the context has only one instance of that type. It just means that a name is assigned to the instance, and the same instance will always be referred to through that name.
A singleton bean. The app initializes the context when starting and adds a bean. In this case, we use the approach with the @Bean annotation to declare the bean. The name of the method becomes the identifier of the bean. Wherever you use that identifier, you get a reference to the same instance.
A scenario class design. Two service classes depend on a repository to implement their use cases. When designed as singleton beans, Spring’s context will have one instance of each of these classes.
The beans are also singleton-scoped when using stereotype annotations to create them. When using @Autowired to request Spring to inject a bean reference, the framework injects the reference to the singleton bean in all the requested places.
When multiple threads access a singleton bean, they access the same instance. If these threads try to change the instance simultaneously, they run into race conditions. The race condition causes unexpected results or execution exceptions if the bean is not designed for concurrency.
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.”
When multiple threads request a certain prototype bean, each thread gets a different instance. This way, the threads cannot run into a race condition.
Each service class requests an instance of CommentRepository. Because CommentRepository is a prototype bean, each service gets a different CommentRepository instance.
A service class uses a mutable object to implement the logic of a use case.
If the CommentProcessor object needs to use an instance of CommentRepository, the easiest way to get an instance is to request a DI. But to do this, Spring needs to know about CommentProcessor, so the CommentProcessor object needs to be a bean in the context.

Summary

  • In Spring, a bean scope defines how Spring creates and manages bean instances.
  • The two main bean scopes are singleton and prototype.
    • Singleton is the default scope. Spring creates one instance, stores it in the context, and always returns the same object when you refer to that bean.
    • Prototype means Spring creates a new instance each time you request that bean.
  • By default, singleton beans are created when the Spring context starts. You can also configure them to be created only when first used.
  • Most applications use singleton beans. Because the same object may be used by multiple threads, singleton beans should usually be immutable.
  • If a singleton bean changes its internal data, you must handle thread safety yourself.
  • Prototype beans are useful when you need mutable objects and want a new instance for each use.
  • Be careful when injecting a prototype bean into a singleton bean. Spring injects the prototype only once, when it creates the singleton. After that, the singleton keeps using the same instance, which usually defeats the purpose of using prototype scope.

FAQ

What does bean scope mean in Spring?Bean scope defines how Spring creates, stores, and returns bean instances in the application context.
What are the two main bean scopes discussed in this chapter?The two main scopes covered are singleton and prototype.
Which bean scope is the default in Spring?Singleton is the default bean scope in Spring.
What does singleton scope mean in Spring?In Spring, singleton means that for a given bean name, Spring returns the same instance every time you ask for it.
Can Spring have multiple singleton beans of the same type?Yes. Spring can have multiple singleton beans of the same type as long as they have different names.
Why should singleton beans usually be immutable?Because singleton beans are shared by the application, and immutability helps avoid concurrency issues and race conditions in multithreaded environments.
What problem can happen if a singleton bean is mutable?If multiple threads modify the same singleton bean instance, race conditions can occur, leading to unexpected results or errors.
What is eager instantiation?Eager instantiation means Spring creates singleton beans when it starts and loads the application context.
What is lazy instantiation?Lazy instantiation means Spring creates a singleton bean only when someone first requests or uses it.
Which instantiation type is default?Eager instantiation is the default behavior for singleton beans in Spring.
Why is eager instantiation usually preferred?It makes dependencies available early, can improve runtime behavior, and helps detect bean creation problems when the application starts.
When might lazy instantiation be useful?Lazy instantiation can be useful when an application has many beans that are not always needed, helping reduce startup time and memory use.
What does prototype scope mean?Prototype scope means Spring creates a new bean instance every time you request it from the context.
When should you consider prototype scope?You should consider prototype scope for beans that need to be mutable or when each use should get a separate instance.
Should every object be a Spring bean?No. An object should be a bean only if Spring needs to manage it and provide framework features such as dependency injection.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Spring Start Here, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Spring Start Here, Second Edition ebook for free