Bean scopes
21 questions in 7 subtopics.
Singleton
What does singleton scope mean in Spring, and how is it different from the singleton design pattern?In tests, two cached Spring contexts exist in one JVM and a singleton cache bean seems to hold different data depending on the test class. Explain.Spring made the shared singleton the default unit of application code. What long-term effects did this have on how Java teams design services, and is it still the right default?Prototype
How does prototype scope behave, and what does the container not do for prototype beans?When would you choose prototype scope, and when is a plain 'new' or a factory method better?Request and session
What are the request and session scopes, and what happens if a request-scoped bean is used outside a web request?A request-scoped bean holding the current tenant id works in controllers but fails inside an@Async method called from a controller. Why, and what are the options?A web application stores a shopping cart in a session-scoped bean. You need to scale to many instances. What do you consider?Request and session scopes tie application code to the servlet request model. As your company adds messaging, batch jobs and async processing, what guidance would you give about using web scopes in shared code?Scoped proxies
Show how to inject a request-scoped bean into a singleton controller, and explain why the proxy is needed.How does a scoped proxy work inside, and what are its costs?A shared library injects a request-scoped 'CurrentUser' proxy into singletons across 50 services. Some services now run the same code from Kafka listeners and fail. How would you redesign it?Prototype inside singleton
A singleton service injects a prototype-scopedReportBuilder with @Autowired, expecting a new builder for each call, but data from one report appears in the next. Why, and how do you fix it?Show how @Lookup method injection works for getting a new prototype from a singleton. What are its limits?Custom scopes
How would you implement and register a custom Spring scope, for example a scope bound to a batch job execution?A team proposes a custom 'tenant' scope so that each tenant gets its own instance of several beans. Evaluate this design.Your multi-tenant platform has used thread-bound context and custom scopes for tenant data for ten years. With virtual threads and more async code, how would you rethink tenant context handling?Thread safety of singletons
This singleton controller returns wrong results under load. Explain the bug:@RestController
class PriceController {
private BigDecimal total;
@GetMapping("/sum")
BigDecimal sum(@RequestParam List<BigDecimal> items) {
total = BigDecimal.ZERO;
for (var i : items) total = total.add(i);
return total;
}
}
No question matches these choices.