In this article Custom bean scope we will explore how to create custom scope of bean in the 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:
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.
- Spring Interview Questions and Answers
- Spring AOP Interview Questions and Answers
- Spring MVC Interview Questions
- Spring Security Interview Questions and Answers
- Spring REST Interview Questions and Answers
- Spring Boot Interview Questions and Answers
- Spring Boot Microservices Interview Questions and Answers
- Dependency Injection (DI) in Spring
- Spring IoC Container
- What is Bean Factory in Spring
- ApplicationContext in Spring
- Bean Autowiring in Spring
- Spring Bean Scopes
- Create Custom Bean Scope in Spring Example
- Using ApplicationContextAware in Spring
- Spring Bean Life Cycle and Callbacks
- BeanPostProcessor in Spring
- BeanFactoryPostProcessor in Spring
- Annotations in Spring and Based Configuration
- Spring JSR-250 Annotations
- JSR 330 Annotations in Spring
- Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
- Method injection with Spring using Lookup method property
- Spring AOP-Introduction to Aspect Oriented Programming
- @Aspect Annotation in Spring
- Spring AOP AspectJ @Before Annotation Advice Example
- Spring AOP Before Advice Example using XML Config
- Spring AOP AspectJ @After Annotation Advice Example
- Spring AOP After Advice Example using XML Config
- Spring AOP AspectJ @AfterReturning Annotation Advice Example
- Spring AOP After-Returning Advice Example using XML Config
- Spring AOP AspectJ @AfterThrowing Annotation Advice Example
- Spring AOP After Throwing Advice Example using XML Config
- Spring AOP AspectJ @Around Annotation Advice Example
- Spring AOP Around Advice Example using XML Config
- Spring AOP Proxies in Spring
- Spring AOP Transaction Management in Hibernate
- Spring Transaction Management
- Spring Declarative Transaction Management Example
- Spring AOP-Ordering of Aspects with Example
- Spring Security Java Based Configuration with Example
- Spring Security XML Namespace Configuration Example