← Назад к вопросам
В чем разница между RequestMapping и PutMapping?
1.2 Junior🔥 211 комментариев
#REST API и микросервисы#Spring Framework
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
В чем разница между RequestMapping и PutMapping
Это вопрос о Spring Framework аннотациях для маршрутизации HTTP запросов. Хотя я ограничен 10 итерациями, отвечу полно на этот важный для Spring разработчиков вопрос.
Быстрое сравнение
| Аспект | @RequestMapping | @PutMapping |
|---|---|---|
| HTTP методы | Все (GET, POST, PUT, DELETE, PATCH и др.) | Только PUT |
| Специализация | Общая аннотация | Специализированная |
| Настроек | Много параметров | Минимум параметров |
| Введена в | Spring 2.5 | Spring 4.3 |
RequestMapping - универсальная аннотация
// @RequestMapping - можно использовать для любого метода
@RestController
public class UserController {
// GET запрос
@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
// POST запрос
@RequestMapping(value = "/users", method = RequestMethod.POST)
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// PUT запрос
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
// DELETE запрос
@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
}
Параметры @RequestMapping
@RequestMapping(
value = "/users", // URL path
method = RequestMethod.PUT, // HTTP method
produces = "application/json", // Response type
consumes = "application/json", // Request type
params = "version=1", // Query parameters
headers = "Authorization=Bearer token" // Headers
)
public User updateUser(@RequestBody User user) {
return userService.save(user);
}
PutMapping - специализированная аннотация
// @PutMapping - только для PUT запросов
@RestController
public class UserController {
// Эквивалент @RequestMapping с method = RequestMethod.PUT
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
}
Параметры @PutMapping
@PutMapping(
value = "/users/{id}", // URL path
produces = "application/json", // Response type
consumes = "application/json" // Request type
)
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.save(user);
}
Эквивалентность
Это одно и то же:
// Вариант 1: с @RequestMapping
@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT)
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
// Вариант 2: с @PutMapping
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
Оба обрабатывают одинаковые запросы:
PUT /api/users/123 HTTP/1.1
Content-Type: application/json
{"name": "John", "email": "john@example.com"}
Когда использовать что
@RequestMapping
// 1. Когда нужна гибкость (несколько методов)
@RequestMapping("/orders")
public class OrderController {
@RequestMapping(method = RequestMethod.GET)
public List<Order> getAll() { }
@RequestMapping(method = RequestMethod.POST)
public Order create(Order order) { }
}
// 2. На уровне класса (базовый path)
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@RequestMapping(method = RequestMethod.GET)
public List<User> getAll() { }
@RequestMapping("/{id}", method = RequestMethod.GET)
public User getById(@PathVariable Long id) { }
}
// 3. Когда нужны сложные параметры (headers, params)
@RequestMapping(
value = "/users",
method = RequestMethod.PUT,
headers = "X-API-Version=2",
params = "format=json"
)
public User updateUser(@RequestBody User user) { }
@PutMapping (и другие специализированные)
// Чище и понятнее для каждого метода
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@GetMapping
public List<User> getAll() { }
@GetMapping("/{id}")
public User getById(@PathVariable Long id) { }
@PostMapping
public User create(@RequestBody User user) { }
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) { }
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) { }
@PatchMapping("/{id}")
public User partialUpdate(@PathVariable Long id, @RequestBody Map<String, Object> updates) { }
}
Все специализированные аннотации
Spring 4.3+ предоставляет удобные шортхенды:
@GetMapping // = @RequestMapping(method = RequestMethod.GET)
@PostMapping // = @RequestMapping(method = RequestMethod.POST)
@PutMapping // = @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping // = @RequestMapping(method = RequestMethod.DELETE)
@PatchMapping // = @RequestMapping(method = RequestMethod.PATCH)
Практический пример REST API
@RestController
@RequestMapping("/api/v1/products")
public class ProductController {
private ProductService productService;
// GET /api/v1/products - получить все
@GetMapping
public List<Product> getAllProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return productService.findAll(page, size);
}
// GET /api/v1/products/123 - получить по ID
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.findById(id);
}
// POST /api/v1/products - создать новый
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productService.save(product);
}
// PUT /api/v1/products/123 - полное обновление
@PutMapping("/{id}")
public Product updateProduct(
@PathVariable Long id,
@RequestBody Product product) {
return productService.update(id, product);
}
// PATCH /api/v1/products/123 - частичное обновление
@PatchMapping("/{id}")
public Product patchProduct(
@PathVariable Long id,
@RequestBody Map<String, Object> updates) {
return productService.patch(id, updates);
}
// DELETE /api/v1/products/123 - удалить
@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.delete(id);
}
}
PUT vs PATCH (важное уточнение)
Оба обновляют, но по-разному:
// Исходный объект:
{
"id": 1,
"name": "Laptop",
"price": 1000,
"category": "Electronics"
}
// PUT - замещает весь объект
@PutMapping("/{id}")
public Product updateProduct(
@PathVariable Long id,
@RequestBody Product product) { // Нужно передать ВСЕ поля
// product должен иметь name, price, category
return productService.update(id, product);
}
// PATCH - обновляет только переданные поля
@PatchMapping("/{id}")
public Product patchProduct(
@PathVariable Long id,
@RequestBody Map<String, Object> updates) { // Только нужные поля
// updates может содержать только {"price": 900}
return productService.patch(id, updates);
}
// Request examples:
// PUT - должен быть полный объект
PUT /api/v1/products/1
{"name": "Laptop", "price": 900, "category": "Electronics"}
// PATCH - только изменяемые поля
PATCH /api/v1/products/1
{"price": 900}
Content Negotiation
// Можно указать produces/consumes для любого метода
@PutMapping(
value = "/{id}",
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Product> updateProduct(
@PathVariable Long id,
@RequestBody Product product) {
return ResponseEntity.ok(productService.update(id, product));
}
Итог
@RequestMapping:
- Универсальная, используется когда нужна гибкость
- На уровне класса для базовых paths
- Когда нужны специальные параметры (headers, params)
@PutMapping:
- Специализирована только для PUT
- Чище и понятнее на уровне методов
- Рекомендуется в современном коде (Spring 4.3+)
Лучшая практика:
- Используй @GetMapping, @PostMapping, @PutMapping, @DeleteMapping на уровне методов
- Используй @RequestMapping на уровне класса для базового path
- Используй @RequestMapping только если нужна специальная логика