Spring Framework 7 API Sürümlendirme
Yinelenen sürüm önekli controller'ları Spring Framework 7'nin yerel API sürümlendirme desteğiyle değiştirin.
// 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);
}
}
// 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);
}
}
Controller yinelemesi yok
Tüm sürümler tek bir controller sınıfında yaşar; yalnızca bireysel işleyici yöntemleri bir version özniteliği taşır.
Merkezi sürüm stratejisi
Tek bir configureApiVersioning çağrısıyla başlıktan URL'ye veya sorgu parametresi sürümlendirmesine geçin.
Kademeli gelişim
İlgisiz uç noktalara dokunmadan veya yeni controller dosyaları oluşturmadan tek bir yönteme yeni bir sürüm ekleyin.
Spring Framework 7.0'dan itibaren kullanılabilir (Java 17+ gerektirir)
Spring Framework 7 öncesinde, API sürümlendirme her sürüm için ayrı controller sınıfları gerektiriyordu (örn. /api/v1/products, /api/v2/products); bu da istek eşlemelerini kopyalıyor ve sürüm mantığını birçok dosyaya yayıyordu. Spring Framework 7, @RequestMapping ve ilgili açıklamalardaki yeni version özniteliği ile WebMvcConfigurer'daki configureApiVersioning kancası aracılığıyla yerel sürümlendirmeyi tanıtıyor. Sürüm, bir istek başlığından, URL yolu segmentinden veya sorgu parametresinden çözümlenebilir — hepsi tek bir yerde kontrol edilir.