Spring Bean scopes with examples

This is 8 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.
There are 5 types of bean scopes supported in spring

  1. singleton – Scopes a single bean definition to a single object instance per Spring IoC container.
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request.
  4. session – Return a single bean instance per HTTP session.
  5. globalSession – Return a single bean instance per global HTTP session.

In many cases,spring’s core scopes i.e.singleton and prototype are used.By default scope of beans is singleton.
Here we will see singleton and prototype scopes in more details.

Singleton bean scope

Example:

For configuring spring in your eclipse ide please refer  hello world example

1.Country.java:

This is simple pojo class having some attributes so here country has name.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.

2.ApplicationContext.xml

3.ScopesInSpringMain.java

This class contains main function.Create ScopesInSpringMain.java under package org.arpit.javapostsforlearning.Copy following content into ScopesInSpringMain.java

4.Run it

When you will run above application,you will get following as output.

When We firstly called getBean and retrieved country object and set countryName to “india” and when second time we called getBean method it did nothing but returned same object with countryName as “india”.

Prototype bean scope

Now we will make change in above xml configuration file.We will add scope attribute in tag and set it to “prototype” and then run it again

ApplicationContext.xml:

Run it again:

When you will run above application,you will get following as output.

When We firstly called getBean and retrieved country object and set countryName to “india”and when second time we called getBean method it returned new object with countryName as “null”.

That’s all about Spring bean scope.
In next post,we will see initializing collections in spring.

Was this post helpful?

Leave a Reply

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