java / expert
Snippet
Implementing a Custom Thread-Local Bean Scope
Custom scopes allow extending Spring's bean management to specific lifecycles. A ThreadScope ensures that a single instance of a bean is shared within one thread but isolated from others, useful for complex background job processing.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ThreadScope implements Scope {private final ThreadLocal<Map<String, Object>> threadLocalScope =ThreadLocal.withInitial(HashMap::new);@Overridepublic Object get(String name, ObjectFactory<?> objectFactory) {return threadLocalScope.get().computeIfAbsent(name, k -> objectFactory.getObject());}@Overridepublic Object remove(String name) {return threadLocalScope.get().remove(name);}@Overridepublic void registerDestructionCallback(String name, Runnable callback) {// Logic for cleaning up resources when thread finishes}}
spring
Breakdown
1
public class ThreadScope implements Scope
Defines a new strategy for how Spring manages and retrieves bean instances.
2
ThreadLocal.withInitial(HashMap::new);
Uses ThreadLocal storage to maintain a separate bean registry for every thread.
3
objectFactory.getObject()
Creates a new bean instance if it does not already exist in the current thread's registry.