Spring SimpleThreadScope Example

By Arvind Rai, October 26, 2021
The SimpleThreadScope is the implementation of Spring Scope interface. The SimpleThreadScope thread scope does not register by default in common contexts. We need explicitly register this scope.
1. Using CustomScopeConfigurer
2. Using ConfigurableBeanFactory.registerScope

Using CustomScopeConfigurer

spring-app.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
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd">

	<bean
		class="org.springframework.beans.factory.config.CustomScopeConfigurer">
		<property name="scopes">
			<map>
				<entry key="thread">
					<bean class="org.springframework.context.support.SimpleThreadScope" />
				</entry>
			</map>
		</property>
	</bean>
	<bean id="city" class="com.concretepage.City" scope="thread" />
</beans> 
City.java
package com.concretepage;
public class City {
  public City() {
	System.out.println("City class Initialized...");
  }
  public String getCityName() {
	return "Varanasi";
  }
} 
SpringDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo {
  public static void main(String... args) {
	AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-app.xml");
	City book = (City) context.getBean("city");
  }
} 
Output
City class Initialized... 

Using ConfigurableBeanFactory.registerScope

 ConfigurableBeanFactory beanFactory=  new DefaultListableBeanFactory();
 Scope threadScope= new SimpleThreadScope();
 beanFactory.registerScope("thread", threadScope); 

Reference

Class SimpleThreadScope

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us