When looking for examples on how to register a custom scope for Spring, almost all of them are using XML based config. For example: http://www.javabeat.net/custom-scope-spring-beans/
In my current project, I don’t use Spring XML configuration, so I needed a way to configure the SimpleThreadScope using Java based configuration.
This can of course be used for all custom scope implementation.
First of all, a BeanFactoryPostProcessor extending class is needed which will called after the BeanFactory is created – i.e. before the Beans are created.
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.SimpleThreadScope;
public class CustomScopeRegisteringBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerScope("thread", new SimpleThreadScope());
}
}
In your Spring config, define a Bean with your BeanFactoryPostProcessor using a static (!) method:
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringConfig {
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
return new CustomScopeRegisteringBeanFactoryPostProcessor();
}
}
Now the scope “thread” can be used for your Spring components. Optionally, a new annotation may be defined for the new scope:
import org.springframework.context.annotation.Scope;
@Scope("thread")
public @interface ThreadScoped {
}
Your Spring components can now be configured with the @ThreadScoped annotation as follows:
@Service
@ThreadScoped
public class MyService {
}