Spring Bean Scope Example

 

Objects managed by Spring IoC container are called beans.

All beans defined in Spring IoC container have, by default, singleton scope, so calling the getBean() method will return always the same instance.

In other hand, if we set the bean scope to prototype value, then the bean can have more than one instance. Each time we call the getBean() method, we will have a new instance.

In this example, we will see the difference between singleton and prototype scopes when defining a Spring bean.

 

1. Technologies used

  • Spring 3.2.8.RELEASE
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7

 

2. Project structure

Spring-Bean-Scope-Example

 

3. Spring dependencies

 

4. Singleton bean

We consider the following class :

File : Lesson

We define a lesson bean for our class, so it will have by default singleton scope.

Then we get two objects of Lesson class from Spring IoC container.

 

When we run the code above, we will have the following output :

The first call : Spring Singleton vs Prototype
The second call : Spring Singleton vs Prototype

 

Calling getTile() method in both objects returns the same value, because the two objects represents the same instance of Lesson class.

 

5. Prototype bean

We change the scope of lesson bean to prototype :

 

If we run the piece of code above, we will have a different output :

The first call : Spring Singleton vs Prototype
The second call : null

 

We can see clearly that we have two instances of Lesson class.

For prototype beans, Spring IoC container creates instances as late as possible. But for singleton beans, they are created by default at the container startup.

 

Download  source code