Sub topic 15
Custom scopes
This chapter assumes you know singleton and prototype scope, scoped proxies, and the bean destruction callbacks covered in earlier chapters. It also assumes you can run a plain Spring application context. Here you will write a custom scope, register it, and see where it can go wrong.
When you need a custom scope
The built-in scopes cover most applications. Singleton gives one instance per container. Prototype gives a new instance per injection. Request, session and application scopes tie a bean to a web lifetime.
A custom scope fits when a bean should live for some other unit of work that Spring does not model. Examples are one tenant, one batch step, one transaction, or one thread. Spring's own projects use this mechanism. Spring Batch's @StepScope and @JobScope and Spring Cloud's @RefreshScope are custom scopes. Spring Framework also ships SimpleThreadScope and SimpleTransactionScope, but neither is registered by default. You must register them under a name yourself.
If a prototype bean created through ObjectProvider solves your problem, use that. Write a custom scope only when instances must be shared within a unit of work and discarded at its end.
The Scope contract
A custom scope implements org.springframework.beans.factory.config.Scope. The container does not create scoped beans itself. It asks the scope to supply them.
| Method | Responsibility |
|---|---|
| `get(name, objectFactory)` | Return the instance for the current context. Call `objectFactory.getObject()` only when none exists yet, and store the result. |
| `remove(name)` | Remove and return the instance. Drop its destruction callback without running it, because the caller destroys the bean. |
| `registerDestructionCallback(name, callback)` | Remember a `Runnable` that destroys the bean. Run it when your scope ends. |
| `resolveContextualObject(key)` | Return a context value for a key, such as `"request"`. Return `null` if you have none. |
| `getConversationId()` | Return an identifier for the current context, or `null`. |
The container calls get every time a scoped bean is requested. It does not cache the result. Your scope owns the instances and their lifetime.
Writing a thread-bound scope
This scope keeps one instance of each bean per thread. It also offers clear(), which runs the destruction callbacks for the current thread's beans.
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
public class ThreadBoundScope implements Scope {
private static final class Holder {
final Map<String, Object> beans = new HashMap<>();
final Map<String, Runnable> callbacks = new HashMap<>();
}
private final ThreadLocal<Holder> holder = ThreadLocal.withInitial(Holder::new);
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> beans = holder.get().beans;
Object bean = beans.get(name);
if (bean == null) {
bean = objectFactory.getObject();
beans.put(name, bean);
}
return bean;
}
@Override
public Object remove(String name) {
Holder h = holder.get();
h.callbacks.remove(name);
return h.beans.remove(name);
}
@Override
public void registerDestructionCallback(String name, Runnable callback) {
holder.get().callbacks.put(name, callback);
}
@Override
public Object resolveContextualObject(String key) {
return null;
}
@Override
public String getConversationId() {
return Thread.currentThread().getName();
}
public void clear() {
Holder h = holder.get();
h.callbacks.values().forEach(Runnable::run);
holder.remove();
}
}get uses an explicit lookup and put instead of computeIfAbsent. Creating one bean can trigger creation of another bean in the same scope. That would modify the map during computeIfAbsent, which HashMap rejects with a ConcurrentModificationException.
A bean that uses the scope
The bean below is stateful, so a shared instance would mix up threads. Its @PreDestroy method shows when the scope releases it.
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(scopeName = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Counter {
private int value;
public void increment() {
value++;
}
public int value() {
return value;
}
@PreDestroy
void release() {
System.out.println("destroying counter, value " + value);
}
}The scope name "thread" is only a string. It must match the name you register the scope under. Without proxyMode, a singleton that receives a Counter would hold a single instance, resolved once at injection time. The proxy defers the lookup to each method call.
Registering the scope
A scope must be registered before any bean that uses it is created. The direct way is registerScope on the bean factory before refresh().
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ThreadBoundScope scope = new ThreadBoundScope();
ctx.getBeanFactory().registerScope("thread", scope);
ctx.register(Counter.class);
ctx.refresh();
Counter counter = ctx.getBean(Counter.class);
counter.increment();
counter.increment();
System.out.println("main thread: " + counter.value());
Thread worker = new Thread(() -> {
counter.increment();
System.out.println("worker: " + counter.value());
scope.clear();
});
worker.start();
worker.join();
scope.clear();
ctx.close();
}
}The program prints:
main thread: 2
worker: 1
destroying counter, value 1
destroying counter, value 2The same counter reference is used by both threads, yet each thread sees its own state. Each scope.clear() call destroys only the calling thread's beans.
In a configuration-driven application, register the scope with a CustomScopeConfigurer. It is a BeanFactoryPostProcessor, so declare its @Bean method static. Otherwise Spring must instantiate the configuration class too early.
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ScopeConfig {
@Bean
static CustomScopeConfigurer customScopeConfigurer() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("thread", new ThreadBoundScope());
return configurer;
}
}What happens on each call
The target bean is registered as scopedTarget.counter. That string is the name your scope receives. When the factory creates the instance, the container also calls registerDestructionCallback for beans that have destruction logic.
Gotchas and failure modes
- You cannot replace built-in scopes. Registering the name
singletonorprototypethrowsIllegalArgumentException. - The scope must be thread-safe. The container may call
getfrom many threads at once. AThreadLocalis safe by construction. A shared map needs a concurrent structure or explicit locking. - Spring never ends your scope for you. Spring calls destruction callbacks only when your scope runs them. If you forget
clear(), beans leak and@PreDestroynever fires. On a thread pool this is worse, because threads are reused and the next task sees the previous task's state. Callclear()in afinallyblock at the end of each unit of work. - Use a scoped proxy when injecting into longer-lived beans. Without it, the singleton keeps whichever instance existed at injection time.
- Fail clearly outside a context. Web scopes throw
IllegalStateExceptionwhen no request is bound. A scope with an explicit start and end should do the same instead of silently creating a stray instance. - Proxy limits.
TARGET_CLASSproxies cannot overridefinalmethods or extendfinalclasses. They also need a visible constructor. UseScopedProxyMode.INTERFACESif the bean implements an interface and you inject that interface. - Built-in helpers.
SimpleThreadScopeis fine for demos. It does not support destruction callbacks and only logs a warning. Use your own scope when you need cleanup.
Exercise
A custom scope's get method creates a bean, but @PreDestroy on that bean never runs, even after the application context closes. What is the likely cause, and how do you fix it?
Show answer
The scope never runs the callback it was given in registerDestructionCallback. The container only hands the scope a Runnable and relies on the scope to run it when its context ends. Closing the application context does not do that for beans in a custom scope. Fix it by running the stored callbacks when the context ends, for example in a clear() method called in a finally block or from a listener on the container's shutdown. Also check that the scope stores the callback keyed by bean name.
Exercise
A singleton service is injected with a bean in your custom "thread" scope, declared without a proxyMode. Two threads call the service. What do they observe, and what change fixes it?
Show answer
Both threads use the same instance, the one created when the singleton was built, so they share state. The scope's get ran only once, at injection. Setting proxyMode = ScopedProxyMode.TARGET_CLASS (or INTERFACES) injects a proxy instead. The proxy calls scope.get on every method call and so resolves a per-thread instance.