Understanding the Bean Scopes in Spring

Introduction

This is a series and it would make a lot of sense if read in a sequence. You can find all the posts under the heading “Spring Beginners to Professionals“. In one of the previous posts, I introduced the concept of scopes for beans. This post is completely focused on explaining the bean scopes in Spring and their usages.

Bean Scopes in Spring

A scope can be considered as a logical boundary within which a bean is deployed and known to the application. There are handful of scopes in Spring.

Before moving on to the scopes defined by Spring, let us  understand how a scope in general can be enforced. Consider a scenario where I have a web application. I want a customer’s information to be available only to him/her during his session. In such a scenario, I have to define the scope of the customer object with the following considerations:

  • It must get created with the login
  • It should be destroyed with logout or may be inactivity for a pre-configured period.

In traditional applications, all this was done using pure Java code and everything was hand coded. A developer had to write the code carefully such that it will destroy the customer object

  • after detecting a log out or
  • certain period of inactivity.

There are many such scenarios, not just limited to the scope of the session of course.

Consider another scenario where a Database Connection Pool has to be created. Now in a typical application, such a connection pool exists one per data source. This is typically implemented as a singleton pattern which guarantees only one connection pool object per data source.

Singleton Scope

Coming back to Spring’s bean scopes. The most important and widely used of them is the singleton scope. In fact this is the default scope for a Spring bean. If no scope information is provided or can be derived in a parent child hierarchy of beans, then by default the bean is created to be deployed in a singleton scope.

However, this singleton is not exactly similar to the objects created using the Singleton Design Pattern. The Singleton Design Pattern dictates hard coding the scope of the object. This enforces creation of only one instance of the particular class per class loader. Spring guarantees exactly one shared bean instance for the given bean definition per IoC container.

How does Spring guarantees a single instance per container?

Once a singleton bean is created by the container, it is kept in a container specific singleton cache. The next time if a request is made with either

  • the id,
  • name or
  • alias of the bean,

it is returned from the cache.

Due to the nature of the beans having singleton scope, it is pretty obvious that these beans can be easily used as a stateless bean.

For e.g.: If you want to create a DAO object, which saves customer data in the database, then the DAO class is created as a singleton.  This works because the DAO class need not care about the state. It should behave the same way irrespective of the Customer object we are trying to persist.

Prototype Scope

Another important scope is the prototype scope. Unlike the singleton scoped beans, the prototype scoped bean deployment results in creation of a new instance of the bean upon request for bean. From our example above, a good candidate for the prototype scope is the Customer bean. Hence, all the stateful objects can be scoped as prototype. To scope a bean as prototype, you need to explicitly mention the scope in the bean metadata like below:

Difference between Singleton and Prototype Scope

From the lifecycle point of view, there are few major differences between the two scopes.

  • The singletons are pre-instantiated whereas the prototype beans are created upon request.
  • Also, the container creates and caches the singleton, hence it is capable of executing all the life cycle methods on them.
  • In case of prototype beans, the container just creates the beans, performs possible initializations  and returns the instance to the caller.
  • Hence, the container cannot execute the destruction lifecycle methods on the prototype beans.
  • The client has to be more responsible to perform the cleanup and prevent resource  leakage.

Can we make the container call the destruction callbacks on prototype beans?

There are ways to make the container perform destruction callbacks on prototype beans. The obvious one is to keep a record of all the prototype beans and invokes the destroy method on them upon work completion.

There are few other scopes which are mostly used in a web environment and I will briefly introduce them in the next post. We will have a in depth discussion about them in another series on Spring MVC.

Summary

This post highlights a major interview question which is asked in almost all the interviews. The difference between Singleton and Prototype Beans or Scope. Another key take away from this post is that the singletons are preinstantiated and cached. This is really important to understand, this is a powerful mechanism in Spring framework, which helps it to guarantee a singleton behavior within the container.

Another big fuss is about injecting prototype beans into singleton beans. I would like you to think over it and we will discuss this in the next post.

Please let me know in comments if you need more explanation on any of these topics. Stay Connected.