Bean Scopes
How many instances of one bean the application needs
A scope determines how the container creates bean instances and how long they live. The two main scopes to understand in Spring Core are singleton and prototype.
By default, a bean has the singleton scope:
within one ApplicationContext, Spring normally uses
the same instance of that bean.
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ReportDraft {
}
prototype has a different idea: every request for that bean from the container
causes a new instance to be created. This is useful when one managed object
should not be shared between independent operations.
A Spring singleton is not a global Singleton
A Spring singleton does not mean “exactly one object in the whole JVM.”
The boundary is a particular container. If you create two independent
ApplicationContext instances, each can have its own singleton bean instance.
In web applications, Spring also provides scopes tied to an HTTP request and session. They will make more sense when we move to Spring MVC; for Spring Core, it is enough to confidently distinguish singleton and prototype.