Sub topic 2
Declaring Supported Versions and How Versions Are Parsed
Assume you know Spring MVC controllers, HTTP headers, and basic Spring Boot configuration. Spring API versioning treats a version as a value extracted from a request, then compares that value with the versions your application supports.
Supported versions and parsing
Declare supported versions explicitly. Spring uses these values to validate incoming requests and to resolve baseline mappings such as 2.0+.
@Configuration
public class ApiVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.setDefaultVersion("1.0");
}
}The supported values are version strings. Use one consistent format across configuration, requests, and mappings. A request carrying X-API-Version: 2.0 resolves to version 2.0. An unsupported value produces a client error instead of silently selecting a handler.
Mapping methods to versions
The version attribute on a request mapping selects a controller method after Spring resolves the request version.
@RestController
@RequestMapping("/accounts")
class AccountController {
@GetMapping(path = "/{id}", version = "1.0")
AccountV1 getV1(@PathVariable long id) {
return new AccountV1(id, "Ada Lovelace");
}
@GetMapping(path = "/{id}", version = "2.0+")
AccountV2 getV2(@PathVariable long id) {
return new AccountV2(id, "Ada", "Lovelace");
}
}Default and required versions
A default version handles requests that omit the version. In the example, an unversioned request behaves as version 1.0. Configure versioning as required when every client must send a version. Then a missing version is rejected instead of using a default.
Fixed versions and baseline versions
A fixed mapping such as version = "1.0" matches only 1.0. A baseline mapping such as version = "2.0+" matches 2.0 and later supported versions. Baselines reduce duplicate methods, but review response compatibility before allowing newer versions to reuse an older handler.
Exercise
Which handler matches a request with version 2.0 when mappings are 1.0 and 2.0+?
Show answer
The 2.0+ mapping matches because it is a baseline for version 2.0 and later.