Spring Bean Scopes Example

In this tutorial we will lean what is the significance of spring bean scopes.

There are 5 types of scopes supported by spring Framework.

singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
session – Return a single bean instance per HTTP session.
request – Return a single bean instance per HTTP request.
globalSession – Return a single bean instance per global HTTP session.

NOTE : By default bean scope is singleton’ , and session,request,globalSession scopes are using in web.

Singleton scope scenario:

If you see in the below configuration file we are not mentioned any bean scope i.e by default it is singleton
 
In above test program initially we got emp1  object for Emplooyee class and setting value as “This First Employee”, later we got another object emp2 and called the getName() on that and  it returned same value what ever we set the value during initialization of Employee object first time.  we can conclude that spring container will return same instance for every time when we configured bean scope as singleton.

 

OUT PUT: 

 

Prototype scope scenario:

If you see in the below configuration file we mentioned bean scope as  prototype.
 
In above test program initially we got emp1  object for Emplooyee class and setting value as “This First Employee”, later we got another object emp2 and called the getName() on that , it returned null.  So we can conclude that spring container will return new instance for every time when we configured bean scope as prototype so it is printed as null.

 

OUT PUT: 

 

Download  Source Code

 

Happy Learning Spring Tutorials … :)

Posted in Spring and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">