Nearby lessons

5 of 35

Spring - Bean Scopes

📌 What You Will Learn
  • Understand Spring - Bean Scopes
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Bean Scopes step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Bean Scopes

In J2SE applications, we are able to define scopes to the data by using the access

modifiers like public, protected, <default> and private.

Similarily, in Spring framework to define scopes to the beans spring framework has

provided the following scopes.

1.singleton Scope[Default Scope]

2.prototype Scope

3.request Scope

4.session Scope

5.globalSession Scope

6.application Scope

7.webSocket scope

  • singleton Scope:

It is default scope in Spring applications.

If we use this scope to the bean then IOCContainer will create Single Bean object for

single bean definition in Spring config file.

This approach will return the same bean object for every time requesting bean object.

When we request bean object first time then IOCContainer will create bean object really

and it will be stored in Cache memory, then , every time accessing bean object ,

IOCContainer will return the same bean object reference value with out creating new

Bean objects.

EX:

beans.xml

<beans>

<bean id="bean1" class="com.durgasoft.MyBean" scope="singleton"/>

<bean id="bean2" class="com.durgasoft.MyBean" scope="singleton"/>

</beans>

System.out.println(ctx.getBean("bean1"));//MyBean@a111

System.out.println(ctx.getBean("bean1"));//MyBean@a111

System.out.println(ctx.getBean("bean2"));//MyBean@a222

System.out.println(ctx.getBean("bean2"));//MyBean@a222

  • prototype Scope:

It is not default Scope in Spring framework.

In Spring applications, if we provide "prototype" scope in bean configuration file then

IOCContainer will ceate a new Bean object at each and every time of calling getBean(--)

method.

EX:

beans.xml

---------

<beans>

<bean id="bean1" class="com.durgasoft.MyBean" scope="prototype"/>

<bean id="bean2" class="com.durgasoft.MyBean" scope="prototype"/>

</beans>

System.out.println(ctx.getBean("bean1"));//MyBean@a111

System.out.println(ctx.getBean("bean1"));//MyBean@a222

System.out.println(ctx.getBean("bean2"));//MyBean@a333

System.out.println(ctx.getBean("bean2"));//MyBean@a444

  • requestScope:

This scope is not usefull in Standalone Applications[Spring Core MOdule], it will be used

in Web applications which are prepared on the basis of Spring Web module.

RequestScope is able to create a seperate bean object for each and every request object.

  • sessionScope:

This Scope will be used web applications which are prepared on the basis of Spring web

module and it is not applicable in Standalone Applications.

sessionScope allows to create a seperate bean object for each and every Session object in

web applications.

  • globalSession Scope:

This scope is not usefull in standard applications, it is usefull in portlet applications which

are prepared on the basis of SPring web module.

globalSession scope allows to create a seperate bean object for each and every portlet

Session.

  • application Scope:

This scope is not usefull in standalone Applications, it is usefull in web applications

prepared on the basis of Spring web momdule.

ApplicationScope allows to create a seperate bean object for each and every

ServletContext object.

  • webSocketScope:

This scope is usefull in web applications which are prepared on the basis of spring web

module.

websocket scope allows to create a seperate bean object for single websocket lifecycle.

If we use the scopes like request, session, globalSession, appplication, webSocket,... in

standalone applications which are prepared on the basis of spring core module then

Container will rise an exception like "java.lang.IllegalStateException".

Note: Spring Framework has provided environment to customize the existed scopes ,

but, it is not suggestible. Spring framework has provided environment to create new

scopes in spring applications.

To define and use custom scopes in Spring Framework we have to use the following

steps.

1.Create User Defined Scope class.

2.Register User defined Scope in Spring beans configuration file.

3.Use User defined Scope to the Beans in beans configuration file.

  • Create User defined Scope class:

a) Declare an user defined class.

b) Implement org.springframework.beans.factory.config.Scope interface to User defined

class.

c) Implement the following Scope interface methods in User defined class.

Bean Scopes

public Object get(String name, ObjectFactory factory)

Example02
JCode Cell
1 
2get(--): It able to generate a bean object from Scope.
3

Bean Scopes

public Object remove(String name)

Example03
JCode Cell
1 
2remove(): It able to remove bean object from Scope.
3

Bean Scopes

EX: IN Session scope, generating sessionId.

public String getConversationId()

Example04
JCode Cell
1 
2getConversationalId(): It able to provide an id value of the scope if any.
3

Bean Scopes

public void registerDestructionCallback(String name, Runnable r)

Example05
JCode Cell
1 
2registerDestructionCallback(): It will be executed when bean object is destroyed inScope
3

Bean Scopes

objects associated with the keys.

public Object resolveContextualObject(String name)

Note: From the above methods, get() and remove() methods are mandatory to

implement and all the remaining methods are optional.

  • Register User defined Scope in Spring beans configuration File:

a) Configure org.springframework.beans.factory.config.CustomScopeConfigurer class as a

bean.

b) Declare "scopes" as property in CustomScopeConfigurer

c) Declare "map" under scopes property.

d) Declare "entry" under the "map".

e) Declare "key" in "entry" with User defined scope name and provide value as USer

defined SCope object.

  • Apply User defined Scope to bean definitions:

Use "scope" attribute in <bean> tag to apply user defined scope.

Note: In the following example, we have defined threadScope as user defined scope,

that is, it able to create a seperate bean object for each and every thread.

Example:

CustomThreadLocal.java

package com.durgasoft.scopes;

import java.util.HashMap;

public class CustomThreadLocal extends ThreadLocal<Object> {

@Override

protected Object initialValue() {

return new HashMap<String, Object>();

}

}

ThreadScope.java

package com.durgasoft.scopes;

import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;

import org.springframework.beans.factory.config.Scope;

public class ThreadScope implements Scope {

Map<String, Object> scope = null;

CustomThreadLocal threadLocal = new CustomThreadLocal();

@Override

public Object get(String name, ObjectFactory objectFactory) {

scope = (Map<String, Object>)threadLocal.get();

Object obj = scope.get(name);

if(obj == null) {

obj = objectFactory.getObject();

scope.put(name, obj);

}

return obj;

}

@Override

public String getConversationId() {

// TODO Auto-generated method stub

return null;

}

@Override

public void registerDestructionCallback(String arg0, Runnable arg1) {

// TODO Auto-generated method stub

}

@Override

public Object remove(String name) {

Object obj = scope.remove(name);

return obj;

}

@Override

public Object resolveContextualObject(String arg0) {

// TODO Auto-generated method stub

return null;

}

}

HelloBean.java

package com.durgasoft.beans;

public class HelloBean {

public HelloBean() {

System.out.println("HelloBean Object is created");

}

public String sayHello() {

return "Hello User from "+Thread.currentThread().getName()+" Scope";

}

}

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.durgasoft.beans.HelloBean;

import com.durgasoft.scopes.ThreadScope;

public class Test {

public static void main(String[] args) {

ApplicationContext context = new

ClassPathXmlApplicationContext("applicationContext.xml");

HelloBean bean1 = (HelloBean)context.getBean("helloBean");

HelloBean bean2 = (HelloBean)context.getBean("helloBean");

System.out.println(bean1);

System.out.println(bean2);

System.out.println(bean1 == bean2);

System.out.println(bean1.sayHello());

System.out.println(bean2.sayHello());

ThreadScope threadScope = (ThreadScope)context.getBean("threadScope");

HelloBean bean3 = (HelloBean)threadScope.remove("helloBean");

System.out.println(bean3);

HelloBean bean4 = (HelloBean)context.getBean("helloBean");

HelloBean bean5 = (HelloBean)context.getBean("helloBean");

System.out.println(bean4);

System.out.println(bean5);

System.out.println(bean4 == bean5);

System.out.println(bean4.sayHello());

System.out.println(bean5.sayHello());

}

}

applicationContext.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.xsd">

<bean id="helloBean" class="com.durgasoft.beans.HelloBean" scope="thread"/>

<bean id="threadScope" class="com.durgasoft.scopes.ThreadScope"/>

<bean id="scopeConfigurer"

class="org.springframework.beans.factory.config.CustomScopeConfigurer">

<property name="scopes">

<map>

<entry key="thread" value-ref="threadScope"/>

</map>

</property>

</bean>

</beans>

  • Java Based Configuration

In Spring, upto Spring2.4 version Spring beans configuration file is mandatory to

configure bean classes and their metadata, but, Right from Spring3.x version Spring beans

configuration file is optional, because, SPring3.x version has provided Java Based

Configuration as replacement for XML documents.

If we want to use Java Based Configuration as an alternative to Spring beans

configuration file in Spring applications then we have to use the following steps.

  • Create Bean classes as per the requirement.
  • Create Beans configuration class with the following annotations.

org.springframework.context.annotation.@Configuration

--> It able to represent a class as configuration class.

org.springframework.context.annotation.@Bean

--> It will be used at method to represent the return object is bean object.

  • In Test class, Create ApplicationContext object with the

org.springframework.context.annotation.Annot

ationConfigpplicationContext implementation class.

ApplicationContext context=new AnnotationConfigApplicationContext(BeanConfig.class);

  • Get Bean object from ApplicationContext by using the following method.

public Object getaBean(Class c)

EX: Bean b=context.getBean(Bean.class);

  • Access business methods from Bean.

Example:

HelloBean.java

package com.durgasoft.beans;

public class HelloBean {

static {

System.out.println("Bean Loading.....");

}

public HelloBean() {

System.out.println("Bean Created....");

}

public String sayHello() {

return "Hello User";

}

}

HelloBeanConfig.java

package com.durgasoft.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import com.durgasoft.beans.HelloBean;

@Configuration

public class HelloBeanConfig {

@Bean

public HelloBean helloBean() {

return new HelloBean();

}

}

Test.java

package com.durgasoft.test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.durgasoft.beans.HelloBean;

import com.durgasoft.config.HelloBeanConfig;

public class Test {

public static void main(String[] args) throws Exception{

ApplicationContext context = new

AnnotationConfigApplicationContext(HelloBeanConfig.class);

HelloBean bean = (HelloBean)context.getBean("helloBean");

System.out.println(bean.sayHello());

}

}

Example06
JCode Cell
1 
2resolveContextualObject(): It will resolve the situation where Multiple Context
3
📝 Key Takeaways
  • Key ideas of Spring - Bean Scopes explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end