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.