Video tayyorlanmoqda

Strong Middle 🌱 Spring

Request scope bean'ni singleton servisga qanday inject qilish mumkin, axir singleton ilova start'da yaratiladi-ku?

Scoped proxy orqali. Singleton'ga haqiqiy bean emas, proxy tushadi; har chaqiruvda proxy joriy HTTP so'rovning nusxasini topib, chaqiruvni o'shanga uzatadi.

📖 Javob

@Component
@RequestScope // = @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
    private String tenantId;
    private String requestId;
    // getter/setter
}

@Component
class TenantFilter extends OncePerRequestFilter {
    private final RequestContext ctx;
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws ServletException, IOException {
        ctx.setTenantId(req.getHeader("X-Tenant"));
        chain.doFilter(req, res);
    }
}

@Service
class InvoiceService {
    private final RequestContext ctx; // aslida proxy
    void create() { String tenant = ctx.getTenantId(); } // shu so'rovning qiymati
}

Ichkarida proxy haqiqiy obyektni RequestContextHolder (ThreadLocal) orqali joriy so'rov atributlaridan oladi.

HTTP so'rovdan tashqarida — @Scheduled, @Async thread, Kafka listener — tegsangiz, No thread-bound request found chiqadi. @Async'ga kerakli qiymatlarni parametr qilib bering.

Amalda ko'p jamoalar request scope o'rniga qiymatni ochiq parametr qilib uzatishni afzal ko'radi: ko'rinib turadi, test qilish ham oson.