← Назад к вопросам

Какая аннотация используется в Spring Boot для создания эндпоинта с path-параметром?

1.0 Junior🔥 211 комментариев
#REST API и микросервисы#Spring Boot и Spring Data#Основы Java

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Spring Boot аннотации для path-параметров

В Spring Boot для создания REST эндпоинтов с path-параметрами используется комбинация аннотаций для маршрутизации и извлечения параметров.

1. @PathVariable - основная аннотация

@PathVariable — аннотация для привязки переменной в URL пути к параметру метода:

@RestController
@RequestMapping("/api/users")
public class UserController {
    
    // Простой path-параметр
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return new User(id, "John Doe");
    }
    
    // URL: /api/users/123 -> id = 123
}

2. Несколько path-параметров

@RestController
@RequestMapping("/api/posts")
public class PostController {
    
    @GetMapping("/{postId}/comments/{commentId}")
    public Comment getComment(
        @PathVariable Long postId,
        @PathVariable Long commentId
    ) {
        return new Comment(commentId, "Post: " + postId);
    }
    
    // URL: /api/posts/5/comments/10
}

3. Явное имя параметра

Если имя переменной в пути отличается от имени параметра:

@RestController
@RequestMapping("/api/articles")
public class ArticleController {
    
    // Явное указание имени пути-переменной
    @GetMapping("/{articleId}")
    public Article getArticle(@PathVariable("articleId") Long id) {
        return new Article(id);
    }
    
    // Или с name
    @GetMapping("/{slug}")
    public Article getBySlug(@PathVariable(name = "slug") String articleSlug) {
        return new Article(articleSlug);
    }
}

4. Опциональные path-параметры (Java 8+)

@RestController
@RequestMapping("/api/items")
public class ItemController {
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getItem(
        @PathVariable(required = false) Long id
    ) {
        if (id == null) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(new Item(id));
    }
}

5. Различные типы данных в path

@RestController
@RequestMapping("/api/resources")
public class ResourceController {
    
    // String параметр
    @GetMapping("/name/{username}")
    public User getUserByName(@PathVariable String username) {
        return new User(username);
    }
    
    // Integer параметр
    @GetMapping("/category/{categoryId}")
    public Category getCategory(@PathVariable Integer categoryId) {
        return new Category(categoryId);
    }
    
    // UUID параметр
    @GetMapping("/document/{docId}")
    public Document getDocument(@PathVariable java.util.UUID docId) {
        return new Document(docId);
    }
    
    // Дата в пути
    @GetMapping("/events/{date}")
    public List<?> getEventsByDate(
        @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) java.time.LocalDate date
    ) {
        return new java.util.ArrayList<>();
    }
}

6. Регулярные выражения в path-параметрах

@RestController
@RequestMapping("/api/files")
public class FileController {
    
    // Только числовые ID
    @GetMapping("/{id:\\d+}")
    public File getFileById(@PathVariable Long id) {
        return new File(id);
    }
    
    // Буквы и цифры (slug)
    @GetMapping("/{slug:[a-zA-Z0-9-]+}")
    public Page getPageBySlug(@PathVariable String slug) {
        return new Page(slug);
    }
}

7. Сложные пути с множественными сегментов

@RestController
@RequestMapping("/api/orgs")
public class OrganizationController {
    
    @GetMapping("/{orgId}/teams/{teamId}/members/{memberId}")
    public Member getMember(
        @PathVariable Long orgId,
        @PathVariable Long teamId,
        @PathVariable Long memberId
    ) {
        return new Member(memberId, orgId, teamId);
    }
    
    // URL: /api/orgs/1/teams/2/members/3
}

8. Другие полезные аннотации вместе с @PathVariable

@RestController
@RequestMapping("/api")
public class CombinedController {
    
    // Path + Query параметры
    @GetMapping("/users/{id}")
    public User getUser(
        @PathVariable Long id,
        @RequestParam(required = false) String details
    ) {
        // /api/users/123?details=full
        return new User(id);
    }
    
    // Path + Body
    @PutMapping("/users/{id}")
    public User updateUser(
        @PathVariable Long id,
        @RequestBody UserDTO userDTO
    ) {
        return new User(id, userDTO.getName());
    }
    
    // Path + Header
    @GetMapping("/data/{key}")
    public String getData(
        @PathVariable String key,
        @RequestHeader("Authorization") String token
    ) {
        return "Data for " + key;
    }
}

9. Валидация path-параметров

@RestController
@RequestMapping("/api/validated")
public class ValidatedController {
    
    @GetMapping("/users/{id}")
    public User getUser(
        @PathVariable @Min(1) @Max(1000000) Long id
    ) {
        return new User(id);
    }
    
    @GetMapping("/posts/{slug}")
    public Post getPost(
        @PathVariable @Pattern(regexp = "[a-z0-9-]+") String slug
    ) {
        return new Post(slug);
    }
}

Сравнение способов передачи параметров

СпособАннотацияПримерВидна в URL
Path параметр@PathVariable/users/123Да
Query параметр@RequestParam/users?id=123Да
Request Body@RequestBodyJSON в телеНет
Header@RequestHeaderHeadersНет

Best Practices

  • Используй @PathVariable для обязательных идентификаторов ресурсов
  • @RequestParam для опциональной фильтрации и параметров
  • Валидируй параметры аннотациями javax.validation
  • Типизируй параметры (Long вместо String для ID)
  • Документируй в Swagger/OpenAPI с @ApiParam