What is the default scope in the web context?
What is the default scope in the web context?
Ngay cả trong ngữ cảnh web, scope mặc định của bean Spring vẫn là singleton. Spring không tự đổi sang request hay session chỉ vì ứng dụng chạy trên web. Một instance bean được tạo cho mỗi ApplicationContext (thường là WebApplicationContext) và dùng chung cho mọi request và mọi người dùng.
@RestController
public class ProductController { // singleton: một instance phục vụ mọi request
private final ProductService service;
public ProductController(ProductService service) { this.service = service; }
}
Các scope chỉ có trong web: muốn dùng phải khai báo rõ ràng, và cần WebApplicationContext:
request: một instance cho mỗi HTTP request.session: một instance cho mỗi HTTP session.application: một instance cho mỗi ServletContext.websocket: một instance cho mỗi phiên WebSocket.@Component
@RequestScope // tương đương @Scope(value = "request", proxyMode = TARGET_CLASS)
public class RequestContext {
private String correlationId;
// getter/setter
}
@Component
@SessionScope
public class ShoppingCart { }
Vì sao cần scoped proxy: bean singleton được tạo một lần lúc khởi động, trong khi bean request chỉ có khi có request. Nếu tiêm trực tiếp, Spring không biết instance nào cần dùng. Giải pháp là proxy: singleton giữ một proxy, mỗi lần gọi phương thức proxy tìm đúng instance của request hiện tại. Các annotation @RequestScope, @SessionScope đã bật sẵn proxyMode = TARGET_CLASS.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.