Scopesmedium3-5 years

A `@Bean @Scope("prototype")` class implements `AutoCloseable`, and its `close()` method never runs even though a `destroyMethod` is configured. Separately, a singleton needs to hold a reference to a request-scoped bean. What's the shared mechanism behind why the first one fails silently, and what makes the second one possible at all?

The container only tracks and destroys objects it keeps a registry entry for — singletons — and a prototype bean is deliberately not one of those: the container builds it, wires it, initialises it, hands it to whoever asked, and then forgets it entirely. There's no registry entry left to call a destroy method on later, so a configured destroyMethod on a prototype bean is silently ignored — the caller that received the object owns it and is responsible for closing it. A singleton holding a request-scoped bean is a different problem with the same root cause (mismatched lifetimes): the singleton is built once, at startup, when no HTTP request exists yet, so there's no real request-scoped instance to inject at that moment. The fix is a scoped proxy — the singleton is handed a stand-in object that looks up the real, current request's instance on every method call, rather than holding a reference to one specific instance.

The lesson behind it →