Spring Bean scopes with examples

Previous
Next

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.ScopesInSpringMain.java

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

3.ApplicationContext.xml

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”.

Source code:

For singleton example:

For prototype example:

In next post,we will see initializing collections in spring.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog