How to choose a bean scope

Each scope in Spring has a different feature, and it falls to us as programmers to know how to utilize those scopes.

In an application, if we have a stateless object and there is no impact on the object creation process then the use of a scope is unnecessary. In contrast, if an object has state then it is advisable to use a scope such as singleton.

When dependency injection is in business, then the singleton scope is not adding much value. In spite of the fact that singletons spare object creation (and afterward garbage collection), synchronization requires us to initialize a singleton bean. Singletons are most valuable for:

  • Configuration of stateful beans
  • Lookup of objects that are costly to build
  • A database association ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.