dineshonjava

Create Custom Bean Scope in Spring Example

There are two main scopes of bean in spring 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's see how to create custom spring bean scope with example.
Create Custom Bean Scope Class
Let's have a look into below class MyThreadScope.java

/**
 * 
 */
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;
 }

}

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.
  • get() method – this method return the bean from the given scope.
  • remove() method – this method remove an object from the scope

Register Created Custom Bean Scope
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's have a look into both configuration as below:

Java Based Configuration:
ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Scope scope = new MyThreadScope();
applicationContext.getBeanFactory().registerScope("myThreadScope", scope);

XML Based Configuration
<?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>

Using the custom scope
In XML
<bean id="myBean" class="com.doj.app.bean.MyBean" scope="myThreadScope"> 
   <property name="name" value="Dinesh"></property>
</bean>

In Java
@Bean
@Scope("myThreadScope")
MyBean myBean(){
   return new MyBean();
}

Test Class for Custom Scope Example
Main.java
/**
 * 
 */
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();
 }

}


Output on Console:
Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy
Mar 24, 2017 7:52:44 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
initialize ThreadLocal
getting object from scope.
Dinesh
All registered Scopes are :
myThreadScope
Mar 24, 2017 7:52:44 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@433c675d: startup date [Fri Mar 24 07:52:44 IST 2017]; root of context hierarchy

Custom Bean Scope Example with Source Code

Download this example from Github.

Create Custom Bean Scope in Spring Example

Spring Related Topics you may like
  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example