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 pool object that is associated with resources

If we consider concurrency, classes defined with a singleton or session scope must be thread-safe, and anything injected in these classes should be thread-safe. On the other hand, the request scope cannot be thread-safe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.29.71