Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

How would you implement and register a custom Spring scope, for example a scope bound to a batch job execution?

We implement org.springframework.beans.factory.config.Scope, whose methods are get, remove, registerDestructionCallback, resolveContextualObject and getConversationId, and store the instances in a map tied to the current job execution, usually reached through a ThreadLocal set by the job launcher. We register the scope with CustomScopeConfigurer or beanFactory.registerScope("job", scope), run the destruction callbacks when the job finishes, and remember that Spring Batch already provides job and step scopes and that Spring ships SimpleThreadScope, which is not registered by default.

Why this question is asked

Most applications never need a custom scope, but implementing one is the best way to understand how scopes work, and there are real cases for it, such as state that should live exactly as long as one batch job run. Interviewers ask for this to see whether we know the Scope contract and the lifecycle details that are easy to get wrong, like destruction callbacks and thread binding. In this answer, we will recap what a scope does, implement a job scope step by step, register and use it, handle cleanup, and finally look at the scopes that already exist.

1A Quick Recap of What a Scope Does

A scope answers one question for the container: for this bean name, which instance should I use right now? Singleton answers "always the same one", prototype "always a new one", request "the one stored in the current HTTP request". A custom scope is our own answer, implemented as an object that the container calls whenever it needs a bean of that scope.

The container passes the scope the bean name and an ObjectFactory, a callback that creates a new instance with full dependency injection and initialisation. The scope decides whether to return a stored instance or to call the factory and store the result. Because a job-scoped bean will usually be injected into singletons, we will also use a scoped proxy, so that each call is routed to the instance of the current job.

2Implementing the Scope

Our job scope keeps one context per running job: a map of bean instances, a map of destruction callbacks and the job id. The launcher binds the context to the thread that runs the job, through a ThreadLocal.

Java
public class JobScope implements Scope {
static final class JobContext {
final String jobId;
final Map<String, Object> beans = new HashMap<>();
final Map<String, Runnable> callbacks = new LinkedHashMap<>();
JobContext(String jobId) { this.jobId = jobId; }
}
private static final ThreadLocal<JobContext> CURRENT = new ThreadLocal<>();
public static void begin(String jobId) { CURRENT.set(new JobContext(jobId)); }
public static void end() {
JobContext ctx = CURRENT.get();
CURRENT.remove();
if (ctx != null) ctx.callbacks.values().forEach(Runnable::run); // destroy job beans
}
private JobContext ctx() {
JobContext c = CURRENT.get();
if (c == null) throw new IllegalStateException("No job is running on thread " + Thread.currentThread().getName());
return c;
}
@Override public Object get(String name, ObjectFactory<?> factory) {
JobContext c = ctx();
Object bean = c.beans.get(name);
if (bean == null) { // not computeIfAbsent: creating one bean may need another
bean = factory.getObject();
c.beans.put(name, bean);
}
return bean;
}
@Override public Object remove(String name) {
JobContext c = ctx();
c.callbacks.remove(name);
return c.beans.remove(name);
}
@Override public void registerDestructionCallback(String name, Runnable callback) {
ctx().callbacks.put(name, callback);
}
@Override public Object resolveContextualObject(String key) {
return "jobId".equals(key) ? ctx().jobId : null;
}
@Override public String getConversationId() {
JobContext c = CURRENT.get();
return c == null ? null : c.jobId;
}
}

Each method has a reason. get() returns the stored instance or creates one through the factory. Notice the comment: creating a job bean can trigger the creation of another job bean it depends on, which calls get() again while we are inside the first call, and HashMap.computeIfAbsent throws ConcurrentModificationException in that case, so a plain get and put is safer. remove() takes a bean out of the scope and forgets its callback. registerDestructionCallback() is how the container tells us what to run when a bean's life ends, such as its @PreDestroy method; the container cannot know when a job ends, so the scope must remember and run these. resolveContextualObject() exposes contextual objects to expressions, so a job-scoped bean can use @Value("#{jobId}"). getConversationId() returns an id for the current scope instance, here the job id, and may return null.

3Registering and Using the Scope

The container must know the scope under a name before any bean uses it. CustomScopeConfigurer is a BeanFactoryPostProcessor that registers scopes from a map, so we declare it as a static @Bean, which lets it run before other beans are created. In code that already has the bean factory, beanFactory.registerScope("job", new JobScope()) does the same.

Java
@Configuration
class JobScopeConfig {
@Bean
static CustomScopeConfigurer jobScopeConfigurer() {
CustomScopeConfigurer c = new CustomScopeConfigurer();
c.addScope("job", new JobScope());
return c;
}
}
@Component
@Scope(value = "job", proxyMode = ScopedProxyMode.TARGET_CLASS)
class JobMetrics {
@Value("#{jobId}") String jobId; // resolved through resolveContextualObject
int processed;
@PreDestroy void report() { log.info("job {} processed {}", jobId, processed); }
}
@Component
class JobLauncher {
private final ImportStep step; // singleton that uses JobMetrics via its proxy
JobLauncher(ImportStep step) { this.step = step; }
void launch(String jobId) {
JobScope.begin(jobId);
try { step.run(); } // all JobMetrics calls go to this job's instance
finally { JobScope.end(); } // logs: job job-42 processed 1200
}
}
Step throughOne job run through the custom scope
JobLauncherJobScopeJobMetrics proxyContainer
begin("job-42")
first call: get("scopedTarget.jobMetrics")
factory.getObject() creates the bean
registerDestructionCallback(@PreDestroy)
later calls: same instance from the map
end(): run callbacks, clear ThreadLocal

6 messages in order. Play them, or step through them one at a time.

The scope stores instances per job and runs their destruction at the end.

Notice the try and finally in the launcher. Ending the scope in finally guarantees that the destruction callbacks run and the ThreadLocal is cleared even if the job fails, so the next job on the same thread starts clean.

4Threads and Cleanup

Binding the scope to a ThreadLocal means it only works on the thread that called begin(). If a job splits work across a thread pool, the worker threads see no job and get the clear IllegalStateException from ctx(). We can propagate the JobContext to workers with a TaskDecorator, but then the map is shared by several threads and must become a ConcurrentHashMap with care for creation races, or the job can pass its context explicitly. Forgetting end() is the other classic bug: the beans stay reachable through the ThreadLocal of a pooled thread, their @PreDestroy never runs, and the next job sees the previous job's instances.

5Scopes That Already Exist

Before writing one, it is worth checking what is already there. Spring Batch provides @JobScope and @StepScope, which do exactly this for Batch jobs, with late binding of job parameters such as @Value("#{jobParameters['date']}"). Spring Framework ships SimpleThreadScope, a scope with one instance per thread, which is not registered by default and, notably, does not run destruction callbacks. Web applications already have request, session and application scopes. A custom scope is worth its complexity only when none of these fit and several beans really need state tied to the same unit of work.

6Follow-up questions

What happens if a job-scoped bean is used outside a job?

With our implementation, the proxy's call reaches get(), ctx() finds no JobContext and throws IllegalStateException with a message naming the thread. A clear message here matters, because the call usually happens deep inside singleton code and the first thing a developer sees is the stack trace.

Why must CustomScopeConfigurer be declared as a static @Bean?

Because it is a BeanFactoryPostProcessor. A non-static @Bean method requires its configuration class to be instantiated first, which forces that class to be created very early, before other post-processors have run, and Spring logs a warning about it. A static method lets Spring call the factory method without creating the configuration instance.

Does the scope need to be thread-safe?

The Scope object itself is shared by the whole container, so any state it holds directly must be thread-safe. In our design each job's state lives in its own JobContext reached through a ThreadLocal, so different jobs on different threads never share a map. Only if one job's context is shared across worker threads do the maps need to be concurrent.

7Conclusion

In this answer, we implemented a job scope by implementing the Scope interface: get() returns or creates the instance for the current job, remove() and registerDestructionCallback() manage instances and their cleanup, resolveContextualObject() exposes the job id to expressions, and getConversationId() identifies the current job. We stored the state in a per-job context bound through a ThreadLocal, registered the scope with a static CustomScopeConfigurer, used it with a scoped proxy, and ran destruction callbacks in a finally block when the job ends. We also saw that Spring Batch's job and step scopes and Spring's SimpleThreadScope may already cover the need.

What to say in the interviewAbout 80 seconds aloud

Open with

I would implement the Scope interface from org.springframework.beans.factory.config. The core is get(name, objectFactory): look up the bean in a map belonging to the current job, and if it is not there, call the object factory, which creates the bean with full injection, store it and return it.

Then, if they want more

I keep the job's state in a small JobContext object, with the bean map, a map of destruction callbacks and the job id, bound to the job's thread through a ThreadLocal that the launcher sets. remove() removes a bean and its callback, registerDestructionCallback() stores the callback the container gives me, resolveContextualObject() can expose the job id to SpEL, and getConversationId() returns the job id.

I register it with a static @Bean CustomScopeConfigurer, or beanFactory.registerScope("job", scope), and declare beans with @Scope(value = "job", proxyMode = TARGET_CLASS) so singletons can use them. The launcher calls begin before the job and end in a finally block, and end runs all destruction callbacks and clears the ThreadLocal, because the container never knows when a job finishes.

Things to watch are worker threads, which do not see the ThreadLocal, and recursive creation inside get(). But first I would check whether Spring Batch's job and step scopes, or SimpleThreadScope, which is not registered by default, already fit.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How would you implement and register a custom Spring scope, for example a scope bound to...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/a2564106f0/