← Назад к вопросам
Где указывается http метод в Spring?
1.6 Junior🔥 161 комментариев
#REST API и микросервисы#Spring Framework
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
# Где указывается HTTP метод в Spring
HTTP метод в Spring указывается через аннотации на методах контроллера. Это делается в трёх основных местах: в аннотациях маршрутов, в конфигурации или через методы.
1. Аннотации на методах контроллера (основной способ)
@GetMapping — GET запросы
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@GetMapping
public List<User> getAllUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findById(id);
}
}
@PostMapping — POST запросы
@PostMapping
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PostMapping("/{id}/email")
public void sendEmail(@PathVariable Long id, @RequestBody EmailRequest email) {
userService.sendEmail(id, email);
}
@PutMapping — PUT запросы
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
@PatchMapping — PATCH запросы
@PatchMapping("/{id}")
public User patchUser(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
return userService.patch(id, updates);
}
@DeleteMapping — DELETE запросы
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
@DeleteMapping
public void deleteAll() {
userService.deleteAll();
}
2. Универсальная аннотация @RequestMapping
@RestController
public class UserController {
// Указываем метод явно
@RequestMapping("/users", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.findAll();
}
@RequestMapping("/users", method = RequestMethod.POST)
public User createUser(@RequestBody User user) {
return userService.save(user);
}
// Или через массив методов
@RequestMapping("/users/{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
public User updateUser(@PathVariable Long id, @RequestBody User user) {
return userService.update(id, user);
}
}
3. На уровне класса контроллера
// @RequestMapping на классе указывает базовый путь
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
// Полный путь: GET /api/v1/users
@GetMapping
public List<User> getAll() { }
// Полный путь: POST /api/v1/users
@PostMapping
public User create(@RequestBody User user) { }
// Полный путь: GET /api/v1/users/{id}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) { }
// Полный путь: PUT /api/v1/users/{id}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) { }
// Полный путь: DELETE /api/v1/users/{id}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) { }
}
4. Полный пример REST API
@RestController
@RequestMapping("/api/v1/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
// GET /api/v1/products
@GetMapping
public ResponseEntity<List<Product>> getAllProducts(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return ResponseEntity.ok(productService.findAll(page, size));
}
// GET /api/v1/products/{id}
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
return ResponseEntity.ok(productService.findById(id));
}
// POST /api/v1/products
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
Product created = productService.save(product);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
// PUT /api/v1/products/{id}
@PutMapping("/{id}")
public ResponseEntity<Product> updateProduct(
@PathVariable Long id,
@RequestBody Product product) {
return ResponseEntity.ok(productService.update(id, product));
}
// PATCH /api/v1/products/{id}
@PatchMapping("/{id}")
public ResponseEntity<Product> partialUpdate(
@PathVariable Long id,
@RequestBody Map<String, Object> updates) {
return ResponseEntity.ok(productService.patch(id, updates));
}
// DELETE /api/v1/products/{id}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
}
5. Несколько методов на одном пути
@RestController
@RequestMapping("/api/v1/comments")
public class CommentController {
// Несколько HTTP методов на одном маршруте
@RequestMapping("/{id}", method = {RequestMethod.GET, RequestMethod.HEAD})
public Comment getComment(@PathVariable Long id) {
return commentService.findById(id);
}
// ИЛИ используя разные аннотации
@GetMapping("/{id}/like")
public void likeComment(@PathVariable Long id) { }
@PostMapping("/{id}/like")
public void addLike(@PathVariable Long id) { }
}
6. Content negotiation — указание типа контента
@RestController
@RequestMapping("/api/v1/data")
public class DataController {
// Только для application/json
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public Data createFromJson(@RequestBody Data data) {
return data;
}
// Только для application/xml
@PostMapping(consumes = MediaType.APPLICATION_XML_VALUE)
public Data createFromXml(@RequestBody Data data) {
return data;
}
// Возвращает JSON
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Data getAsJson() {
return new Data();
}
// Возвращает XML
@GetMapping(produces = MediaType.APPLICATION_XML_VALUE)
public Data getAsXml() {
return new Data();
}
}
7. Обработка исключений
@RestController
@RequestMapping("/api/v1/orders")
public class OrderController {
@PostMapping
public ResponseEntity<Order> createOrder(@RequestBody Order order) {
// Может вернуть разные коды в зависимости от результата
return ResponseEntity.status(HttpStatus.CREATED).body(order);
}
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(OrderNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(e.getMessage()));
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ErrorResponse> handleValidation(ValidationException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(new ErrorResponse(e.getMessage()));
}
}
Сравнение способов
| Способ | Использование | Преимущества |
|---|---|---|
| @GetMapping | GET запросы | Короче, понятнее |
| @PostMapping | POST запросы | Специализирована |
| @PutMapping | PUT запросы | Специализирована |
| @PatchMapping | PATCH запросы | Специализирована |
| @DeleteMapping | DELETE запросы | Специализирована |
| @RequestMapping | Любые методы | Гибче, явнее |
✅ Лучшие практики
// ✓ Используй специализированные аннотации
@GetMapping("/users")
// ✓ Указывай полный путь на уровне класса
@RequestMapping("/api/v1/users")
// ✓ Возвращай ResponseEntity для контроля кода ответа
return ResponseEntity.status(HttpStatus.CREATED).body(user);
// ✓ Используй правильные HTTP методы
// GET — получение (безопасен, идемпотентен)
// POST — создание
// PUT — полное обновление
// PATCH — частичное обновление
// DELETE — удаление
// ✓ Не смешивай логику в одном методе
@GetMapping("/{id}")
public User get(@PathVariable Long id) { }
@PostMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) { }