Video tayyorlanmoqda

Junior 🌱 Spring

Controller klassi ustiga qo'yilgan @RequestMapping nima beradi?

Klass ustidagi @RequestMapping controller'dagi hamma metod uchun umumiy URL prefiksi (kerak bo'lsa produces/consumes ham) beradi. Metoddagi yo'l shunga qo'shiladi.

📖 Javob

@RestController
@RequestMapping(path = "/api/v1/customers", produces = MediaType.APPLICATION_JSON_VALUE)
class CustomerController {

    @GetMapping               // GET /api/v1/customers
    List<CustomerDto> all() { ... }

    @GetMapping("/{id}")      // GET /api/v1/customers/{id}
    CustomerDto one(@PathVariable Long id) { ... }

    @PostMapping("/{id}/block")  // POST /api/v1/customers/{id}/block
    void block(@PathVariable Long id) { ... }
}

Prefiksni har metodda takrorlamaysiz, versiyani (/v1) bitta joyda o'zgartirasiz. produces, consumes, headers ham hamma metodga o'tadi.

Klass ustida odatda HTTP metod yozilmaydi. Agar @RequestMapping(method = GET) deb yozsangiz, bu ichidagi hamma metodlarga qo'shiladi va POST endpoint'laringiz kutilmaganda ishlamay qoladi.

Ikki controller bir xil URL va metodni e'lon qilsa, Spring start'da "Ambiguous mapping" bilan to'xtaydi — yaxshi, xato prodga yetmaydi.