Sub topic 12
Prototype scope
This chapter assumes you know the singleton scope, constructor injection, and the init and destroy callbacks from earlier chapters.
What prototype scope does
A bean with prototype scope is created anew each time something asks the container for it. Singleton scope creates one shared instance. Prototype scope creates a fresh one for every getBean() call and every injection point.
You set it with @Scope:
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class Job {
}Use prototype for beans that hold state belonging to one caller, such as a unit of work, a builder, or a per-task context.
What the container does and does not do
For a prototype bean, the container runs the instantiation and initialization phases. It calls the constructor, injects dependencies, runs the Aware callbacks, applies every BeanPostProcessor, and runs the init callbacks (@PostConstruct, afterPropertiesSet, initMethod).
The container then hands the instance to the caller and forgets it. It keeps no reference to the bean. Because of this, it never calls @PreDestroy, DisposableBean.destroy, or destroyMethod on a prototype bean, not even when the context closes.
If a prototype holds a resource such as a file handle or a connection, the caller must release it. One option is a close() method that the caller invokes. Another is a custom BeanPostProcessor that tracks the instances and cleans them up itself.
The singleton injection trap
A singleton is created once, so its dependencies are injected once. If you inject a prototype into a singleton through a field or constructor, the singleton keeps the same Job for its whole life. The prototype behaves like a singleton.
Ask for a new instance on demand with ObjectProvider:
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
@Service
class JobRunner {
private final ObjectProvider<Job> jobs;
JobRunner(ObjectProvider<Job> jobs) {
this.jobs = jobs;
}
Job newJob() {
return jobs.getObject();
}
}Each call to getObject() goes back to the container and returns a new Job. You can check this:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
JobRunner runner = ctx.getBean(JobRunner.class);
System.out.println(runner.newJob() == runner.newJob());
}
}
}This prints false. If you injected Job directly into JobRunner, the same comparison would print true.
Common errors
- Expecting
@PreDestroyto run on a prototype. It never runs, and no warning is logged. - Injecting a prototype into a singleton and assuming each method call gets a new one.
- Calling
getBean()from inside business code through an injectedApplicationContext.ObjectProviderdoes the same job without coupling your class to the context. - Forgetting that prototypes are created lazily. A prototype is never created at startup, so a failing constructor appears at the first request.
Exercise
A prototype bean opens a file in @PostConstruct and closes it in @PreDestroy. After the application context closes, the file is still open. Why, and what are two ways to fix it?
Show answer
The container does not track prototype instances, so it never calls @PreDestroy on them. Fix it by having the caller close the bean explicitly (for example through a close() method), or by registering a custom BeanPostProcessor that keeps references to created instances and releases them when the context shuts down.