Home  >  Spring Core

Example of SimpleThreadScope in Spring

By Arvind Rai, April 16, 2013
SimpleThreadScope in spring has been introduced from spring 3.0. It is the scope which is not registered with spring container by default. SimpleThreadScope is the scope in which a bean has the life cycle affiliated to thread life cycle. To use SimpleThreadScope we need to register it in our XML or in java code.
app-conf.xml
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.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="testA" class="com.concretepage.A"  scope="thread" />
</beans> 

SpringTest.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("app-conf.xml");
		context.getBean("testA");
	}
} 
Output
Bean A is initialized
 
Note: we can register bean in java class also. Look into the below code snippet.
 ConfigurableBeanFactory beanFactory=  new DefaultListableBeanFactory();
 Scope threadScope= new SimpleThreadScope();
 beanFactory.registerScope("thread", threadScope); 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us