Monday, November 25, 2013

Changing Default Spring Bean Scope

02.04.2013
 | 2572 views | 
 By default, Spring beans are scoped singleton, meaning there’s only one instance for the whole application context. For most applications, this is a sensible default; then sometimes, not so much. This may be the case when using a custom scope, which is the case, on the product I’m currently working on. I’m not at liberty to discuss the details further: suffice to say that it is very painful to configure each and every needed bean with this custom scope.
Since being lazy in a smart way is at the core of developer work, I decided to search for a way to ease my burden and found it in the BeanFactoryPostProcessor class. It only has a single method - postProcessBeanFactory(), but it gives access to the bean factory itself (which is at the root of the various application context classes).
From this point on, the code is trivial even with no prior experience of the API:
01.public class PrototypeScopedBeanFactoryPostProcessor implementsBeanFactoryPostProcessor {
02. 
03.@Override
04.public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
05. 
06.for (String beanName : factory.getBeanDefinitionNames()) {
07. 
08.BeanDefinition beanDef = factory.getBeanDefinition(beanName);
09. 
10.String explicitScope = beanDef.getScope();
11. 
12.if ("".equals(explicitScope)) {
13. 
14.beanDef.setScope("prototype");
15.}
16.}
17.}
18.}
The final touch is to register the post-processor in the context . This is achieved by treating it as a simple anonymous bean:
1.xml version="1.0" encoding="UTF-8"?>
5. 
6.<beanclass="ch.frankel.blog.spring.scope.PrototypeScopedBeanFactoryPostProcessor"/>
7. 
8.</beans>
Now, every bean which scope is not explicitly set will be scoped prototype.

No comments: