API-Versionierung in Spring Framework 7
Ersetze duplizierte, versionspräfixierte Controller durch die native API-Versionierungsunterstützung von Spring Framework 7.
// 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);
}
}
Keine Controller-Duplizierung
Alle Versionen leben in einer Controller-Klasse; nur die einzelnen Handler-Methoden tragen ein version-Attribut.
Zentralisierte Versionsstrategie
Wechsle von Header- zu URL- oder Query-Parameter-Versionierung in einem einzigen configureApiVersioning-Aufruf.
Inkrementelle Weiterentwicklung
Füge eine neue Version zu einer Methode hinzu, ohne nicht verwandte Endpunkte zu berühren oder neue Controller-Dateien zu erstellen.
Verfügbar seit Spring Framework 7.0 (erfordert Java 17+)
Vor Spring Framework 7 erforderte API-Versionierung separate Controller-Klassen pro Version (z. B. /api/v1/products, /api/v2/products), was Request-Mappings duplizierte und Versionslogik über viele Dateien verteilte. Spring Framework 7 führt native Versionierung über ein neues version-Attribut in @RequestMapping und verwandten Annotationen sowie einen configureApiVersioning-Hook in WebMvcConfigurer ein. Die Version kann aus einem Request-Header, einem URL-Pfadsegment oder einem Query-Parameter aufgelöst werden — alles zentral gesteuert.