When you create a bean definition, you create a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, as with a class, you can create many object instances from a single recipe.
You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition but also control the scope of the objects created from a particular bean definition. This approach is powerful and flexible, because you can choose the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes. The Spring Framework supports six scopes, four of which are available only if you use a web-aware ApplicationContext
. You can also create a custom scope.
스코프를 bean definition에서 지정할 수 있다는건, 자바 코드로 내려가지 않고도 설정정보만으로도 빈의 스코프를 지정할 수 있다는 것을 의미. 이는 컴포넌트들에게 유연함을 부여한다.
ScopeDescription
1️⃣ singleton
(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
2️⃣ prototype
Scopes a single bean definition to any number of object instances.
3️⃣ request
Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext
.
4️⃣ session
Scopes a single bean definition to the lifecycle of an HTTP Session
. Only valid in the context of a web-aware Spring ApplicationContext
.
5️⃣ application
Scopes a single bean definition to the lifecycle of a ServletContext
. Only valid in the context of a web-aware Spring ApplicationContext
.
💡 ServletContext란?
6️⃣ websocket
Scopes a single bean definition to the lifecycle of a WebSocket
. Only valid in the context of a web-aware Spring ApplicationContext
.