5 The Spring Context: Bean scopes and lifecycle

 

This chapter covers

  • Using the singleton bean scope
  • Using eager and lazy instantiation for singleton beans
  • Using the prototype bean scope

Up to now, we discussed several essential things about object instances managed by Spring (beans). We covered the important syntaxes you need to know to create beans, and we discussed establishing relationships among beans (including the necessity of using abstractions). But we didn’t focus on how and when Spring creates the beans. From this perspective, we’ve only relied on the framework’s default approaches.

I chose not to discuss this aspect earlier in the book because I wanted you to focus on the syntaxes you’ll need upfront in your projects. However, production apps’ scenarios are complex, and sometimes relying on the framework’s default behavior is not enough. For this reason, in this chapter, we need to go a little bit deeper with our discussion on how Spring manages the beans in its context.

Spring has multiple different approaches for creating beans and managing their lifecycle, and in the Spring world, we name these approaches “scopes”. In this chapter, we discuss two scopes that you’ll often find Spring apps. These scopes are named singleton and prototype.

Note

Later, in chapter 9, we discuss three more bean scopes that apply to web applications: request, session, and application.

5.1    Using the singleton bean scope

 
 
 
 

5.1.1   How singleton beans work

 
 

5.1.2   Singleton beans in real-world scenarios

 
 
 

5.1.3   Using eager and lazy instantiation

 
 

5.2    Using the prototype bean scope

 
 
 
 

5.2.1   How prototype beans work

 
 
 
 

5.2.2   Prototype beans in real-world scenarios

 
 

5.3    Summary

 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest