To create a prototype-scoped bean in Spring, annotate the bean with @Scope("prototype") (or @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)). The container then creates a new instance every time the bean is requested, instead of sharing the single default singleton.
Spring instantiates, wires and initialises a prototype bean, then hands it to the caller and forgets it. It does not call destruction callbacks on prototype beans, so you must release their resources yourself.
| Aspect | Singleton (default) | Prototype |
|---|---|---|
| Instances per container | One | One per request for the bean |
| Created | At startup (eagerly, by default) | On each lookup or injection |
| Destruction callbacks | Called on context close | Not called by Spring |
| Good for | Stateless services | Stateful, short-lived objects |
Use prototype scope only for objects that hold per-use state. Stateless services should remain singletons.
Put @Scope next to @Bean in a @Configuration class.
Each getBean call returned a separate object with its own count.
For component scanning, annotate the class itself:
In legacy XML configuration, use the scope attribute:
Injecting a prototype bean into a singleton resolves it only once, when the singleton is created. The singleton then keeps the same prototype instance forever, which defeats the purpose.
There are three clean ways to get a fresh instance on each use.
ObjectProvider is the idiomatic choice in current Spring:
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS) injects a proxy that delegates to a new instance on each method call, which suits cases where you want to keep injecting the bean directly. Be aware that each call on the proxy hits a new instance, so state does not persist between calls. Alternatively, a @Lookup method on a singleton returns a new prototype per call.
Spring runs initialisation callbacks (@PostConstruct, afterPropertiesSet, initMethod) on prototype beans, but never @PreDestroy or destroyMethod. If the bean holds connections, files or threads, close them explicitly or implement AutoCloseable and let the caller manage it.
Lazily, each time it is requested through getBean, injection into a new target, or an ObjectProvider. It is not created at startup.
It was probably injected into a singleton, which resolves it once. Use ObjectProvider, @Lookup or a scoped proxy.
No. Spring does not manage the full lifecycle of prototypes, so destruction callbacks are skipped.
Each caller gets its own instance, so there is no sharing by default. If you hand one instance to several threads, you must synchronise it yourself.
Mark a bean with @Scope("prototype") to get a new instance on every request. Remember that Spring will not destroy it, and that injecting it into a singleton fixes one instance unless you use ObjectProvider, @Lookup or a scoped proxy.