Springs - SPLessons

Spring Bean scopes

Chapter 23

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Spring Bean scopes

shape Introduction

When Configuring a bean in the Spring configuration file, We can also configure the scope of that bean. In order to configure a scope, we use an attribute with bean tag called “scope“.

In Spring, 1.x version attribute name is a singleton, but 2.x it is changed to scope.

Spring Framework support different type of scopes.

  1. singleton
  2. prototype
  3. request
  4. session
  5. global session

1. The singleton scope

If scope value is assigned to singleton, the Spring IOC container creates exactly one instance of the object defined by the bean definition. By default, Spring IoC container makes a Spring bean as a singleton that respects to “Id”.

As long as client applications are asking for an object of a bean from the container by passing the same id as a parameter in getBean() method then container returns the same object.

1. Create the project directory structure.

2. Add the required spring jar files through Add external jar files.

3. create the java class under the package folder.


package com.splessons;
public class BeanClass 
   private String userName;
   public void setUserName(String userName)
	this.userName = userName;
   public String getUserName() 
	 System.out.println("Hello, " + userName);
	return userName;


package com.splessons;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");

      BeanClass beanClass1 = (BeanClass) context.getBean("BeanScope");

          beanClass1.setUserName(" Welcome to SPLessons ");

      BeanClass beanClass2 = (BeanClass) context.getBean("BeanScope");

4. Create the bean configuration file under source (src) folder.

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

<beans xmlns="http://www.springframework.org/schema/beans"

   <bean id="BeanScope" class="com.splessons.BeanClass" 


5. Run the application and display the output like

Spring – Related Information
Spring Overview
Spring Architecture
Spring Environment Setup

Spring Basic Example
Are you looking for a Job? Stay Updated with Limitless Notifications!!

Join us on Telegram Channel