chapter five

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

We’ve discussed several essential topics about object instances managed by Spring (beans), the important syntaxes you need to know to create beans, and we even covered establishing relationships among beans (including the necessity of using abstractions). But we haven’t yet focused on how and when Spring creates the beans in the first place. From this perspective, we’ve only relied on the framework’s default approaches.

I chose not to discuss this aspect earlier because I wanted you to focus on the syntaxes you’ll need up-front. But production apps’ scenarios are complex, and sometimes relying on the framework’s default behavior is not enough. For this reason, 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. Two scopes you’ll often find in Spring apps are singleton and prototype.

5.1 Using the singleton bean scope

5.1.1 Singleton beans in real-world scenarios

5.1.2 Using eager and lazy instantiation

5.2 Using the prototype bean scope

5.2.1 Prototype beans in real-world scenarios

5.3 Questions

5.4 Summary