14.

【Spring】@PathVariableアノテーションとは

編集
この記事の要点
  • @PathVariableURL パスの一部を変数として取得するアノテーション
  • 例: @GetMapping("/users/{id}") + @PathVariable Long id
  • 複数の path 変数も可: /users/{userId}/posts/{postId}
  • パス名と引数名が違う場合: @PathVariable("userId") Long id
  • 正規表現で制約可: {id:[0-9]+}

 

基本的な使い方

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // /api/users/123 → id = 123
        return userService.findById(id);
    }
}

Spring が URL の {id} 部分を変数として受け取り、メソッド引数に注入します。型変換は自動(String → Long, Integer, UUID 等)。

複数のパス変数

@GetMapping("/{userId}/posts/{postId}")
public Post getPost(
    @PathVariable Long userId,
    @PathVariable Long postId
) {
    // /api/users/1/posts/42 → userId=1, postId=42
    return postService.findByUserAndPost(userId, postId);
}

パス変数名と引数名が異なる場合

@GetMapping("/{user-id}")
public User getUser(@PathVariable("user-id") Long id) {
    // ハイフン入り変数名は Java 識別子にできないので明示
    return userService.findById(id);
}

// 別名で受け取りたい場合
@GetMapping("/{id}")
public User getUser(@PathVariable("id") Long userId) {
    return userService.findById(userId);
}

正規表現で制約

@GetMapping("/{id:[0-9]+}")
public User getById(@PathVariable Long id) {
    // 数字のみマッチ (/api/users/abc は 404)
    return userService.findById(id);
}

@GetMapping("/{slug:[a-z0-9-]+}")
public User getBySlug(@PathVariable String slug) {
    // 小文字英数字 + ハイフンのみ (slug)
    return userService.findBySlug(slug);
}

@GetMapping("/{uuid:[0-9a-f-]{36}}")
public User getByUuid(@PathVariable String uuid) {
    // UUID 形式のみ
    return userService.findByUuid(uuid);
}

Map で全部受け取る

@GetMapping("/{userId}/posts/{postId}/comments/{commentId}")
public Comment get(@PathVariable Map pathVars) {
    Long userId = Long.parseLong(pathVars.get("userId"));
    Long postId = Long.parseLong(pathVars.get("postId"));
    Long commentId = Long.parseLong(pathVars.get("commentId"));
    return commentService.find(userId, postId, commentId);
}

オプショナルなパス変数

パス変数自体はオプショナルにできません(URL パターンで吸収するか、別エンドポイントを用意)。代替: クエリパラメータで @RequestParam(required = false)

// パス変数の有無で別メソッド
@GetMapping("/users")
public List listAll() {
    return userService.findAll();
}

@GetMapping("/users/{id}")
public User getOne(@PathVariable Long id) {
    return userService.findById(id);
}

// あるいは URL パターン両方マッチ (Spring 5.3+ で {*path} は可変パス)
@GetMapping({"/users", "/users/{id}"})
public Object users(@PathVariable Optional id) {
    return id.map(userService::findById)
             .map(Object.class::cast)
             .orElse(userService.findAll());
}

型変換

String → 各種型への変換が自動で行われます:

変換
Long / Integer標準
UUID標準
enum標準(名前 or @JsonValue)
LocalDate / LocalDateTime@DateTimeFormat 必要
カスタム型Converter 実装
@GetMapping("/{date}")
public Report getDaily(
    @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date
) {
    // /api/reports/2026-05-15 → date = 2026-05-15
    return reportService.byDate(date);
}

// カスタム enum
public enum UserRole { ADMIN, USER, GUEST }

@GetMapping("/role/{role}")
public List byRole(@PathVariable UserRole role) {
    // /api/users/role/ADMIN → role = UserRole.ADMIN
    return userService.findByRole(role);
}

エラーハンドリング

型変換失敗

/api/users/abc のように Long に変換できない場合、デフォルトでは 400 Bad Request + MethodArgumentTypeMismatchException

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity handle(MethodArgumentTypeMismatchException ex) {
        ErrorResponse err = new ErrorResponse(
            "INVALID_PATH_VARIABLE",
            "Invalid value for path variable: " + ex.getName()
        );
        return ResponseEntity.badRequest().body(err);
    }
}

@PathVariable vs @RequestParam vs @RequestBody

使う場面アノテーションURL 例
リソースの ID(必須)@PathVariable/users/123
フィルタ・ページング(オプショナル)@RequestParam/users?status=active&page=2
大量データ・POST ボディ@RequestBodyPOST /users + JSON ボディ

関連記事

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. @After
  2. @Autowired
  3. @Bean
  4. @Before
  5. @Column
  6. @Component
  7. @Configuration
  8. @Controller
  9. @Data
  10. @Entity
  11. @GeneratedValue
  12. @Id
  13. @Modifying
  14. @PathVariable
  15. @PropertySource
  16. @Repository
  17. @RequestBody
  18. @RequestMapping
  19. @ResponseBody
  20. @RestController
  21. @Service
  22. @SpringBootApplication
  23. @Table
  24. @Transactional
  25. @Value