Bạn có chắc chắn muốn xóa bài viết này không ?
Spring Bean Scope Annotation: @RequestScope | @SessionScope | @ApplicationScope
Spring Framework new release 4.3 make some Web Improvements. Among that, it simplifies way to implement Bean Scopes (Request, Session and Application scopes) using Annotation: @RequestScope | @SessionScope | @ApplicationScope. They are only valid in the context of a web-aware Application.
- Spring Bean Scope - Singleton and Prototype
- Spring Bean Scope using Annotation – Singleton, Prototype, Request, Session, Global Session, Application
- Java 1.8
- Maven 3.3.9
- Spring Tool Suite – Version 3.8.1.RELEASE
- Spring Boot: 1.5.1.RELEASE
1. GoalTo build a simple application using @RequestScope and @SessionScope annotation that shows you the way request, session act and the difference between them. Beside, we also have a lean introduction of @ApplicationScope.
2. Scope AnnotationWith old approach, we usually annotate the class which bean has scope by:
@Scope(value = [scope], proxyMode = ScopedProxyMode.TARGET_CLASS)
- Proxy Mode TARGET_CLASS: is used for creating AOP proxy of the bean. We must do it when injecting short lived bean scope (request, session...) to long lived bean scope (singleton, prototype) or injecting prototype to singleton scope.
- We have some type of scope:
- singleton: only one instance is created (default scope)
- prototype: new instance is created everytime prototype bean is referenced.
- request: one instance for a single HTTP request.
- session: one instance for an HTTP Session
- globalSession: one instance for a global HTTP Session. Typically only valid when used in a Portlet context.
- application: Scopes a single bean definition to the lifecycle of a ServletContext (Only valid in the context of a web-aware Spring ApplicationContext).