5 The Spring context: Bean scopes and life cycle

 

This chapter covers

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

Thus far we have 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 up-front 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 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 life cycle, and in the Spring world we name these approaches scopes. In this chapter, we discuss two scopes you’ll often find in Spring apps: 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

Summary