Springs - SPLessons
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. BeanClass.java [java] 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; } } [/java] MainApplication.java [java]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 "); beanClass1.getUserName(); BeanClass beanClass2 = (BeanClass) context.getBean("BeanScope"); beanClass2.getUserName(); } } [/java] 4. Create the bean configuration file under source (src) folder. applicationcontext.xml [xml]<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="BeanScope" class="com.splessons.BeanClass" scope="singleton"> </bean> </beans>[/xml] 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