<div dir="ltr" style="text-align: justify;">
<p>In this article Custom bean scope we will explore how to create custom scope of bean in the spring example. There are two main <a href="https://dineshonjava.com/understanding-bean-scopes/">scopes of bean in spring</a> singleton and prototype but spring allow us to create custom bean scope too through the interface Scope in the spring Example. As of Spring 2.0, we can define custom spring bean scope as well as modify existing spring bean scopes (except singleton and prototype scopes). So let&#8217;s see how to create custom spring bean scope with example.</p>
<div id="ads-id" align="center"></div>
<h2><b>Create Custom Bean Scope Class</b></h2>
<p>Let&#8217;s have a look into below class <b>MyThreadScope.java</b></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.app.scope; 
 
import java.util.HashMap; 
import java.util.Map; 
 
import org.springframework.beans.factory.ObjectFactory; 
import org.springframework.beans.factory.config.Scope; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class MyThreadScope implements Scope { 
 
 private final ThreadLocal<;Object>; myThreadScope = new ThreadLocal<;Object>;() { 
 protected Map<;String, Object>; initialValue() { 
 System.out.println("initialize ThreadLocal"); 
 return new HashMap<;String, Object>;(); 
 } 
 }; 
 
 @SuppressWarnings("unchecked") 
 @Override 
 public Object get(String name, ObjectFactory<;?>; objectFactory) { 
 Map<;String, Object>; scope = (Map<;String, Object>;) myThreadScope.get(); 
 System.out.println("getting object from scope."); 
 Object object = scope.get(name); 
 if(object == null) { 
 object = objectFactory.getObject(); 
 scope.put(name, object); 
 } 
 return object; 
 } 
 
 @Override 
 public String getConversationId() { 
 return null; 
 } 
 
 @Override 
 public void registerDestructionCallback(String name, Runnable callback) { 
 
 } 
 
 @Override 
 public Object remove(String name) { 
 System.out.println("removing object from scope."); 
 @SuppressWarnings("unchecked") 
 Map<;String, Object>; scope = (Map<;String, Object>;) myThreadScope.get(); 
 return scope.remove(name); 
 } 
 
 @Override 
 public Object resolveContextualObject(String name) { 
 return null; 
 } 
 
} 
 
</pre>
<p>As above class for custom scope MyThreadScope, we have implemented org.springframework.beans.factory.config.Scope interface to create a own custom scope in the spring container. This interface contain five methods. But following two mandatory methods have to override to create custom spring bean scope.</p>
<ul style="text-align: left;">
<li><b>get() method</b> – this method return the bean from the given scope.</li>
<li><b>remove() method</b> – this method remove an object from the scope</li>
</ul>
<div style="background-color: #f2f9fc; border: 1px solid #c9e6f2; border-radius: 3px; padding: 16px; line-height: 1.45;"><span style="color: red; font-size: x-large; text-align: center;"><b>Popular Tutorials</b></span></p>
<ul style="text-align: left;">
<li><b><a href="https://dineshonjava.com/spring-tutorial/"><em><strong>Spring Tutorial</strong> </em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-web-mvc-framework-chapter-38/"><strong><em>Spring MVC Web Tutorial </em></strong></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-spring-boot-a-spring-boot-complete-guide/"><strong>Spring Boot Tutorial</strong> </a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-take-baby-step-to-secure/"><em>Spring Security Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/"><em>Spring AOP Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/using-spring-jdbc-framework-chapter-32/"><em>Spring JDBC Tutorial</em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-hateoas-hypermedia-driven-restful-web-service/"><em><strong>Spring HATEOAS </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/microservices-with-spring-boot/"><em><strong>Microservices with Spring Boot</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/jax-rs-web-service-tutorial/"><strong><em>REST Webservice</em> </strong></a></b></li>
<li><b><a href="https://dineshonjava.com/core-java-baby-step-to-be-best-java-ian/"><em><strong>Core Java </strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/hibernate-3-on-baby-steps/"><em><strong>Hibernate Tutorial</strong></em></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-batch-process-with-example/"><strong><em>Spring Batch</em> </strong></a></b></li>
</ul>
</div>
<h2><b>Register Created Custom Bean Scope</b></h2>
<p>After creating the custom bean scope, we have to register it with the spring container. So there are two way to register it. Either by it programmatic registration or we can do it via using XML based configuration. Let&#8217;s have a look into both configuration as below:</p>
<h3><b>Java Based Configuration:</b></h3>
<pre class="highlight">ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 
Scope scope = new MyThreadScope(); 
applicationContext.getBeanFactory().registerScope("myThreadScope", scope); 
</pre>
<h3><b>XML Based Configuration</b></h3>
<pre class="highlight"><;?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 class="org.springframework.beans.factory.config.CustomScopeConfigurer">; 
 <;property name="scopes">; 
 <;map>; 
 <;entry key="myThreadScope">; 
 <;bean class="com.doj.app.scope.MyThreadScope"/>; 
 <;/entry>; 
 <;/map>; 
 <;/property>; 
 <;/bean>; 
 
 <;bean id="myBean" class="com.doj.app.bean.MyBean" scope="myThreadScope">; 
 <;property name="name" value="Dinesh">;<;/property>; 
 <;/bean>; 
<;/beans>; 
</pre>
<h3><b>Using the custom scope</b></h3>
<p><b>In XML</b></p>
<pre class="highlight"><;bean id="myBean" class="com.doj.app.bean.MyBean" scope="myThreadScope">; 
 <;property name="name" value="Dinesh">;<;/property>; 
<;/bean>; 
</pre>
<p><b>In Java</b></p>
<pre class="highlight">@Bean 
@Scope("myThreadScope") 
MyBean myBean(){ 
 return new MyBean(); 
} 
</pre>
<h3><b>Test Class for Custom Scope Example</b><br />
<b></b></h3>
<p><b>Main.java</b></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.app.test; 
 
import org.springframework.context.ConfigurableApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
import com.doj.app.bean.MyBean; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class Main { 
 /** 
 * @param args 
 */ 
 public static void main(String[] args) { 
 ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 
 MyBean myBean = applicationContext.getBean(MyBean.class); 
 System.out.println(myBean.getName()); 
 System.out.println("All registered Scopes are : "); 
 for(String scope : applicationContext.getBeanFactory().getRegisteredScopeNames()){ 
 System.out.println(scope); 
 } 
 applicationContext.close(); 
 } 
 
} 
 
</pre>
<p><b>Output on Console:</b></p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px;">Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh<br />
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy<br />
Mar 24, 2017 7:52:44 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions<br />
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]<br />
initialize ThreadLocal<br />
getting object from scope.<br />
Dinesh<br />
All registered Scopes are :<br />
myThreadScope<br />
Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose<br />
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy</div>
<h2><b>Custom Bean Scope Example with Source Code</b></h2>
<p><a href="https://github.com/DOJ-SoftwareConsultant/Spring-Custom-Bean-Scope" target="_blank" rel="noopener"><b>Download this example from Github</b></a>.</p>
<div class="separator" style="clear: both; text-align: center;"><img src="https://i0.wp.com/dineshonjava.com/wp-content/uploads/2017/03/spring-custom-bean-scope-example.png" border="0" /></div>
<p> ;</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px;"><span style="color: red; font-size: x-large; text-align: center;"><b>Spring Related Topics you may like</b></span></p>
<ul>
<li><b><a href="https://dineshonjava.com/interview-questions-on-spring/"><span style="color: red;">Spring Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-interview-questions-and-answers/"><span style="color: red;">Spring AOP Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-mvc-interview-questions-and-answers/"><span style="color: red;">Spring MVC Interview Questions</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-interview-questions-and-answers/"><span style="color: red;">Spring Security Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-rest-web-services-interview-questions-and-answers/"><span style="color: red;">Spring REST Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-boot-interview-questions-and-answers/"><span style="color: red;">Spring Boot Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-boot-microservices-interview-questions-answers/"><span style="color: red;">Spring Boot Microservices Interview Questions and Answers</span></a></b></li>
<li><b><a href="https://dineshonjava.com/dependency-injection-in-spring/"><span style="color: red;">Dependency Injection (DI) in Spring </span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-ioc-container/"><span style="color: red;">Spring IoC Container</span></a></b></li>
<li><b><a href="https://dineshonjava.com/what-is-bean-factory-in-spring/"><span style="color: red;">What is Bean Factory in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/application-context-in-spring/"><span style="color: red;">ApplicationContext in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/bean-autowiring-in-spring/"><span style="color: red;">Bean Autowiring in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/understanding-bean-scopes/"><span style="color: red;">Spring Bean Scopes</span></a></b></li>
<li><b><a href="https://dineshonjava.com/create-custom-bean-scope-in-spring-example/"><span style="color: red;">Create Custom Bean Scope in Spring Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/using-applicationcontextaware-in-spring/"><span style="color: red;">Using ApplicationContextAware in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/bean-lifecycle-and-callbacks/"><span style="color: red;">Spring Bean Life Cycle and Callbacks</span></a></b></li>
<li><b><a href="https://dineshonjava.com/writing-beanpostprocessor-in-spring/"><span style="color: red;">BeanPostProcessor in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/writing-beanfactorypostprocessor-in/"><span style="color: red;">BeanFactoryPostProcessor in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/annotations-in-spring-and-based/"><span style="color: red;"> Annotations in Spring and Based Configuration</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-jsr-250-annotations/"><span style="color: red;">Spring JSR-250 Annotations</span></a></b></li>
<li><b><a href="https://dineshonjava.com/jsr-330-annotations-in-spring/"><span style="color: red;">JSR 330 Annotations in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/stereotype-annotations-in-spring/"><span style="color: red;">Spring @Component, @Repository, @Service and @Controller Stereotype Annotations</span></a></b></li>
<li><b><a href="https://dineshonjava.com/method-injection-with-spring-using-lookup-method-property/"><span style="color: red;">Method injection with Spring using Lookup method property</span></a></b></li>
<li><b><a href="https://dineshonjava.com/introduction-to-aop-in-spring/"><span style="color: red;">Spring AOP-Introduction to Aspect Oriented Programming</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aspect-annotation/"><span style="color: red;">@Aspect Annotation in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-aspectj-before-annotation-advice-example/"><span style="color: red;"> Spring AOP AspectJ @Before Annotation Advice Example<br />
</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-before-advice-example-using-xml-config/"><span style="color: red;"> Spring AOP Before Advice Example using XML Config</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-aspectj-after-annotation-advice-example/"><span style="color: red;"> Spring AOP AspectJ @After Annotation Advice Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-after-advice-example-using-xml-config/"><span style="color: red;"> Spring AOP After Advice Example using XML Config</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-aspectj-after-returning-annotation-advice-example/"><span style="color: red;"> Spring AOP AspectJ @AfterReturning Annotation Advice Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-after-returning-advice-example-using-xml-config/"><span style="color: red;"> Spring AOP After-Returning Advice Example using XML Config</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-aspectj-after-throwing-annotation-advice-example/"><span style="color: red;"> Spring AOP AspectJ @AfterThrowing Annotation Advice Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-after-throwing-advice-example-using-xml-config/"><span style="color: red;"> Spring AOP After Throwing Advice Example using XML Config</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-aspectj-around-annotation-advice-example/"><span style="color: red;"> Spring AOP AspectJ @Around Annotation Advice Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-around-advice-example-using-xml-config/"><span style="color: red;"> Spring AOP Around Advice Example using XML Config</span></a></b></li>
<li><b><a href="https://dineshonjava.com/understanding-aop-proxies-chapter-31/"><span style="color: red;">Spring AOP Proxies in Spring</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-transaction-management-in/"><span style="color: red;"> Spring AOP Transaction Management in Hibernate</span></a></b></li>
<li><b><a href="https://dineshonjava.com/transaction-management-in-spring/"><span style="color: red;">Spring Transaction Management</span></a></b></li>
<li><b><a href="https://dineshonjava.com/declarative-transaction-management/"><span style="color: red;">Spring Declarative Transaction Management Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-aop-ordering-of-aspects-with-example/"><span style="color: red;">Spring AOP-Ordering of Aspects with Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-java-based-configuration-with-example/"><span style="color: red;">Spring Security Java Based Configuration with Example</span></a></b></li>
<li><b><a href="https://dineshonjava.com/spring-security-xml-namespace-configuration-example/"><span style="color: red;">Spring Security XML Namespace Configuration Example</span></a></b></li>
</ul>
<p> ;</p>
</div>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/spring-aop-tutorial-with-example-aspect-advice-pointcut-joinpoint/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/spring-certification-without-pivotal-training-course/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '42'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…