Điều gì xảy ra khi ứng dụng Spring Boot (web) khởi động với hai bean sau?
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class TenantContext {
private String tenantId;
// getter, setter
}
@Service
public class InvoiceService {
private final TenantContext tenant;
public InvoiceService(TenantContext tenant) { this.tenant = tenant; }
}
Xem đáp án và giải thích
Bean singleton được tạo một lần lúc khởi động, nên dependency của nó cũng phải có ngay lúc đó. Bean request/session scope chỉ tồn tại khi có request, vì vậy muốn inject vào singleton phải dùng scoped proxy: Spring inject một proxy, mỗi lần gọi method proxy mới tìm instance của request hiện tại. @RequestScope và @SessionScope mặc định đã bật proxyMode = TARGET_CLASS, còn @Scope("request") thì không.