Enterprise 中級

バージョンプレフィックスを持つ重複コントローラーをSpring Framework 7のネイティブAPIバージョニングサポートに置き換える。

✕ Spring Boot 2/3
// Version 1 controller
@RestController
@RequestMapping("/api/v1/products")
public class ProductControllerV1 {
    @GetMapping("/{id}")
    public ProductDtoV1 getProduct(
            @PathVariable Long id) {
        return service.getV1(id);
    }
}

// Version 2 — duplicated structure
@RestController
@RequestMapping("/api/v2/products")
public class ProductControllerV2 {
    @GetMapping("/{id}")
    public ProductDtoV2 getProduct(
            @PathVariable Long id) {
        return service.getV2(id);
    }
}
✓ Spring Framework 7+
// Configure versioning once
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureApiVersioning(
            ApiVersionConfigurer config) {
        config.useRequestHeader("X-API-Version");
    }
}

// Single controller, version per method
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @GetMapping(value = "/{id}", version = "1")
    public ProductDtoV1 getV1(@PathVariable Long id) {
        return service.getV1(id);
    }

    @GetMapping(value = "/{id}", version = "2")
    public ProductDtoV2 getV2(@PathVariable Long id) {
        return service.getV2(id);
    }
}
このコードに問題がありますか? お知らせください。
🗂️

コントローラーの重複なし

すべてのバージョンが1つのコントローラークラスに収まり、個々のハンドラーメソッドだけにversion属性を付けます。

⚙️

バージョン戦略の集中管理

ヘッダー・URLパス・クエリパラメーターによるバージョニングの切り替えが1つのconfigureApiVersioning呼び出しで完結します。

📈

段階的な進化

新バージョンを1つのメソッドに追加するだけで、関連のないエンドポイントや新しいコントローラーファイルへの影響はありません。

旧来のアプローチ
手動URLパスバージョニング
モダンなアプローチ
ネイティブAPIバージョニング
JDKバージョン
17
難易度
中級
Spring Framework 7 APIバージョニング
利用可能

Spring Framework 7.0(Java 17以上が必要)以降、利用可能

Spring Framework 7以前のAPIバージョニングでは、バージョンごとに別々のコントローラークラスが必要(例:/api/v1/products・/api/v2/products)で、リクエストマッピングが重複し、バージョンロジックが多数のファイルに分散していました。Spring Framework 7では@RequestMappingなどのアノテーションにversion属性が追加され、WebMvcConfigurerにconfigureApiVersioningフックが導入されました。バージョンはリクエストヘッダー・URLパスセグメント・クエリパラメーターから解決でき、すべて1か所で制御できます。

共有 𝕏 🦋 in