Sub topic 15
Custom scopes
This chapter assumes you know singleton and prototype scopes, scoped proxies, and how @Scope works. Custom scopes are rarely needed. Reach for one only when the built-in scopes don't match the lifetime you need, such as one instance per tenant, per thread, or per batch job.
How a scope works
A scope is an object that stores bean instances and decides when to return an existing one. The container still builds the bean from its definition. When something asks for a bean in a custom scope, the container calls Scope.get(name, objectFactory). Your scope looks in its own storage. If it finds an instance, it returns it. Otherwise it calls objectFactory.getObject(), stores the new instance, and returns it.
The org.springframework.beans.factory.config.Scope interface has five methods:
| Method | Purpose |
|---|---|
| `get` | Return the existing instance, or create one through the `ObjectFactory` |
| `remove` | Drop an instance from storage and return it, or `null` |
| `registerDestructionCallback` | Receive a callback to run when the scope ends |
| `resolveContextualObject` | Expose contextual values, such as the request for web scopes. May return `null` |
| `getConversationId` | Return an identifier for the current context, or `null` |
A thread-bound scope
This scope keeps one instance of each bean per thread. Spring ships a similar SimpleThreadScope, but it is not registered by default and it doesn't run destruction callbacks.
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class MapThreadScope implements Scope {
private final ThreadLocal<Map<String, Object>> beans =
ThreadLocal.withInitial(HashMap::new);
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> map = beans.get();
Object bean = map.get(name);
if (bean == null) {
bean = objectFactory.getObject();
map.put(name, bean);
}
return bean;
}
@Override
public Object remove(String name) {
return beans.get().remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
// This simple scope never runs destruction callbacks.
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return Thread.currentThread().getName();
}
}Registering and using the scope
Register the scope under a name with CustomScopeConfigurer. Declare its @Bean method static so the configurer is created early, before the beans that use the scope.
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Configuration
class ScopeConfig {
@Bean
static CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("thread", new MapThreadScope());
return configurer;
}
}
@Component
@Scope(value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
class ThreadContext {
private String user;
void setUser(String user) { this.user = user; }
String getUser() { return user; }
}You can also call beanFactory.registerScope("thread", scope) on a ConfigurableBeanFactory directly.
Common errors
- Unknown scope name.
No Scope registered for scope name 'thread'means the scope was not registered before the bean was requested. Check that the configurer@Beanmethod isstatic. - Scope mismatch. Injecting a custom-scoped bean into a singleton without a proxy gives you one instance, fixed at startup. Set
proxyMode, or inject anObjectProvider. - Leaked state. With a thread pool, threads are reused. Clear the scope's storage at the end of each task, or the next task sees stale beans.
Exercise
A singleton service has a bean in your custom "thread" scope injected as a plain field, with no proxy mode. Every thread sees the same instance. Why, and how do you fix it?
Show answer
The singleton is created once, so the container calls Scope.get once and injects that single instance. Scope.get is not called again. Fix it by setting proxyMode on @Scope, such as ScopedProxyMode.TARGET_CLASS, so the singleton holds a proxy that calls Scope.get on each method call. Injecting an ObjectProvider also works.