Spring bean scopes by R4R Team

Spring bean scopes:-
The core of spring framework is itís bean factory and mechanisms to create and manage such beans inside Spring container. The beans in spring container can be created in five scopes.That are as follows:
1 singleton : scopes to a single object instance per Spring IOC Container.
2 prototype : scopes to any number of object instances
3 request : scopes to the lifecycle of a single HTTP request, available only when using a web aware ApplicationContext.
4 session : scopes to the lifecycle of an HTTP session, also available only when using a web aware ApplicationContext.
5 global session : scopes to the lifecycle of a global HTTP session, also available only when using a web aware ApplicationContext.

The singleton scope:
If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.
The default scope is always singleton however, when you need one and only one instance of a bean, you can set the scope property to singleton in the bean configuration file, as shown below:

id=".." class=".." scope="singleton">

Example : Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:

1 Create a project with a name SpringTest and create a package com.r4r under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example.
3 Create Java classes Demo and MainApp under the com.r4r package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.


package com.r4r;

public class Demo {

private String message;

public void setMessage(String message){

this.message = message;


public void getMessage(){

System.out.println("Your Message :- " + message);



package com.r4r;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

Demo d1 = (Demo) context.getBean("demo");

d1.setMessage("Spring is very Easy.");


Demo d2 = (Demo) context.getBean("demo");




"1.0" encoding="UTF-8"?>





id="demo" class="com.r4r.Demo" scope="singleton">

Output: Your Message:-Spring is very Easy.

              Your Message:-Spring is very Easy.   

Leave a Comment:
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!