Java Login


Hello guys, is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.

     << Previous
Next >>     

Spring Bean Scope

When you define a bean in the configuration file, you are just defining the structure of the bean or it is just a class. With that definition, you can create any number of instances. Here the advantage of the bean is that, you are not only allowed to define the dependencies for the beans, you also can set the scope for the beans. The spring framework supports following five scopes. Out of which three scopes are supported only in web ApplicationContext.

5 types of bean scopes supported :

  • singleton - Return a single bean instance per Spring IOC container
  • prototype - Return a new bean instance each time when requested
  • request - Return a single bean instance per HTTP request. *
  • session - Return a single bean instance per HTTP session. *
  • globalSession - Return a single bean instance per global HTTP session.

Example of Spring Bean Scope (Singleton and Prototype)

package beanScope;

public class HelloWorld {
private String name;

public String getName() {
return name;

public void setName(String name) { = name;



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<bean id="prototype" class="beanScope.HelloWorld"

<bean id="singleton" class="beanScope.HelloWorld"


package beanScope;

import org.springframework.context.ApplicationContext;

public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new

HelloWorld objA = (HelloWorld) context.getBean("singleton");
System.out.println("---------SINGLETON SCOPE------------");
objA.setName("User 1");
System.out.println("Your Message : " + objA.getName());

HelloWorld objB = (HelloWorld) context.getBean("singleton");
System.out.println("Your Message : " + objB.getName());

HelloWorld objC = (HelloWorld) context.getBean("prototype");
System.out.println("---------PROTOTYPE SCOPE------------");
objC.setName("User 2");
System.out.println("Your Message : " + objC.getName());

HelloWorld objD = (HelloWorld) context.getBean("prototype");
System.out.println("Your Message : " + objD.getName());


When you run this program then you will see in output that in singleton scope value is same but in prototype scope value is different.

-----------SINGLETON SCOPE--------------
Your Message : User 1
Your Message : User 1
-----------PROTOTYPE SCOPE--------------
Your Message : User 2
Your Message : null

     << Previous
Next >>