Spring Bean Scopes

In this example , we will see bean scopes in spring container . In Spring 5 below scopes (websocket) have been  newly introduced –

SCOPE DESCRIPTION
singleton (default) Single bean object instance per spring IoC container
prototype Opposite to singleton, it produces a new instance each and every time a bean is requested.
request Return a single bean instance per HTTP request.Only valid in web-aware Spring ApplicationContext.
session Return a single bean instance per HTTP session.Only valid in web-aware Spring ApplicationContext.
application A single instance will be created and available during complete lifecycle of ServletContext.Only valid in web-aware Spring ApplicationContext.
websocket A single instance will be created and available during complete lifecycle of WebSocket.Only valid in web-aware Spring ApplicationContext.

Tools used to create below project – 

  1. Spring 5.0.7.RELEASE
  2. Maven 3.3
  3. Java 8
  4. Eclipse Neon.2

Github Link :   Download

Step 1: Create Simple Maven Project with Spring Configuration

Step 2: Configure maven dependencies

Below pom.xml file contains the dependencies required for spring project –

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.myjavablog</groupId>
<artifactId>SpringBeanScopesDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringBeanScopesDemo</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>5.0.7.RELEASE</spring.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<!-- Spring 5 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

</dependencies>
</project>

Below project structure will be created for you by Eclipse .

 

 

 

 

 

 

 

 

 

Step 3:  Create City.java under com.myjavablog.beans package –

City.java

package com.myjavablog.beans;

/**
* @author anupb
*
*/
public class City {

String cityName;

public String getcityName() {
return cityName;
}

public void setcityName(String cityName) {
this.cityName = cityName;
}

}

These are bean files where we have only getters and setters defined.

Step 4: Create ApplicationContext.xml under /src/main/resources-

ApplicationContext.xml

<div id="crayon-5b537011533c5704156605-2" class="crayon-line crayon-striped-line">

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- Default Singleton scope bean -->
<bean id="CitySingletonBean" class="com.myjavablog.beans.City">
</bean>

<!-- Proptotype scope bean-->
<bean id="CityPrototypeBean" class="com.myjavablog.beans.City" scope="prototype">
</bean>

</beans>

</div>

Step 5: Create a BeanScopesMain.java under com.myjavablog package –

package com.myjavablog;

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

import com.myjavablog.beans.City;

public class BeanScopesMain {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext beanFactory = new ClassPathXmlApplicationContext("ApplicationContext.xml");

//Default Singleton scope bean
City singletonBeanInstance1 = (City) beanFactory.getBean("CitySingletonBean");
singletonBeanInstance1.setcityName("Pune");
System.out.println("Singleton Bean value: "+singletonBeanInstance1.getcityName()+"---------- Instance hashcode: "+singletonBeanInstance1.hashCode());

City singletonBeanInstance2 = (City) beanFactory.getBean("CitySingletonBean");
System.out.println("Singleton Bean value: "+singletonBeanInstance2.getcityName() +"---------- Instance hashcode: "+singletonBeanInstance2.hashCode());

//Proptotype scope bean
City prototypeBeanInstance1 = (City) beanFactory.getBean("CityPrototypeBean");
prototypeBeanInstance1.setcityName("Pune");

System.out.println("Prototype Bean value: "+prototypeBeanInstance1.getcityName()+"---------- Instance hashcode: "+prototypeBeanInstance1.hashCode());

City prototypeBeanInstance2 = (City) beanFactory.getBean("CityPrototypeBean");
prototypeBeanInstance2.setcityName("Pune");

System.out.println("Prototype Bean value: "+prototypeBeanInstance2.getcityName()+"---------- Instance hashcode: "+prototypeBeanInstance2.hashCode());

}
}

We have created ApplicationContext which actually loads bean definitions from XML configuration.

Output:

Singleton Bean value: Pune---------- Instance hashcode: 1509563803
Singleton Bean value: Pune---------- Instance hashcode: 1509563803
Prototype Bean value: Pune---------- Instance hashcode: 684874119
Prototype Bean value: null---------- Instance hashcode: 1157740463

In case of Singleton bean, When We firstly called getBean and retrieved city object and set cityName to “Pune” and when second time we called getBean method it did nothing but returned same object with cityName as “Pune”. Both the objects has same hashcodes as its same object.

In case of Prototype bean,When We firstly called getBean and retrieved city object and set cityName to “Pune”and when second time we called getBean method it returned new object with cityName as “null”. Both the objects has different hashcodes shows these are completely different and created freshly.

Step 6: Clean and install project

Now run the maven clean install phase as below –

Command:  mvn clean install

OR

Right click on project -> Debug As -> Maven build . Below popup will come up –


 

 

 

 

 

 

 

Step 7: Run the spring application as Java Application

 

 

 

 

 

 

 

 

Output:

Singleton Bean value: Pune---------- Instance hashcode: 1509563803
Singleton Bean value: Pune---------- Instance hashcode: 1509563803
Prototype Bean value: Pune---------- Instance hashcode: 684874119
Prototype Bean value: null---------- Instance hashcode: 1157740463

Leave a Comment

Bitnami