When you create a bean definition, you create a set of rules for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a set of rules is important because it means that, just like a class, you can create multiple instances of objects from a single rule set.
Not only can you control the various dependencies and configuration values that must be attached to an object created from a particular bean definition, but you can also control the scope of objects created from a particular bean definition. This approach has great benefits and is flexible because you can choose the scope of the objects you create through configuration, rather than having to prepare the object's scope at the Java class level. Beans can be defined to be deployed to one of several scopes. The Spring Framework supports six scopes, four of which are only available if you use the web-aware ApplicationContext. You can also create a special scope.
The following table describes the supported scopes:
| Scope | Description |
|---|---|
| singleton object |
(Default) Applies the scope of a single bean definition to a single object instance for each Spring IoC container. |
| prototype |
Applies the scope of a single bean definition to any number of object instances. |
| request |
Applies the scope of a single bean definition to the lifecycle of a single HTTP request. Thus, for each new HTTP request, a new bean instance is created based on a single bean definition. Valid only in the context of the web-aware |
| session |
Applies the scope of a single bean definition for the HTTP |
| application |
Applies the scope of a single bean definition to the |
| websocket |
Applies the scope of a single bean definition for the |
SimpleThreadScope. For instructions on registering this or any other custom scope, see
Using a custom scope.
GO TO FULL VERSION