Card 01/ 07
Bean Scopes: Singleton and Prototype
One shared instance for the whole application, or a new one every time a bean is requested.
A bean's scope decides how many instances of it exist and how long each one lives. The default is singleton: the container creates exactly one instance and hands that same object to everyone who asks for it, for as long as the application runs. prototype is the alternative: a new instance every time the bean is requested.
A RideService is used by every request an application handles. As a singleton there is one of it, created at startup. As a prototype there would be a new one each time another bean, or a call to getBean, asked for it.
The container tracks a singleton for its whole life: it creates it, hands it out, and destroys it when the context closes. A prototype it creates, initialises and hands over, and then forgets. Web applications add shorter scopes as well, such as request, which creates one instance per web request.
Most beans should be singletons. A RideService or a repository holds no per-caller data, so it has no reason to exist twice. The cost of a singleton appears when it holds mutable state (fields whose values change while the application runs), because every caller then shares those fields.
So choosing a scope is really a question about state: a bean with no changing fields is a singleton, and a bean that collects data for one caller at a time needs a shorter scope.
← → move through sections and cards