Sub topic 6
Mapping controller methods to versions
This chapter covers the version attribute on request mapping annotations. It assumes you can write @RestController classes with @GetMapping and @PathVariable, and that you configured a version resolver in the previous chapters. Here the focus is how Spring chooses between handler methods that share one path.
The version attribute
@RequestMapping and its composed forms (@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping) accept a version attribute. It is one more request condition, next to path, HTTP method, headers and media types. A method matches only when the path, the method and the version all match.
The attribute is a string and comes in two forms:
- A fixed version, such as
"1.0", matches only that version. - A baseline version, such as
"2.0+", matches that version and any later supported version.
Version mapping needs versioning to be enabled first. In this chapter the configuration is the header-based one from the earlier chapters:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ApiVersionConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@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 resolver reads the header, the parser turns the text into a version object, and Spring checks it against the supported list. Only after that does handler mapping use the version attribute.
Two methods, one path
Two handler methods can share the same path and HTTP method as long as their versions differ. Without the version attribute, Spring would report an ambiguous mapping at startup.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/accounts")
public class AccountController {
record AccountV1(long id, String name) {}
record AccountV2(long id, String firstName, String lastName) {}
@GetMapping(path = "/{id}", version = "1.0")
public AccountV1 getV1(@PathVariable long id) {
return new AccountV1(id, "Ada Lovelace");
}
@GetMapping(path = "/{id}", version = "2.0+")
public AccountV2 getV2(@PathVariable long id) {
return new AccountV2(id, "Ada", "Lovelace");
}
}With this controller and the configuration above, a request such as GET /accounts/1 with the header X-API-Version: 2.0 returns {"id":1,"firstName":"Ada","lastName":"Lovelace"}. The same request with X-API-Version: 1.0 returns {"id":1,"name":"Ada Lovelace"}.
The version is not part of the URL here. Both methods answer /accounts/{id}, and the header selects between them. The same mapping works if you later switch the resolver to a path segment, a query parameter or a media type parameter. The controller code stays the same, and only the configuration changes.
How a request is matched
Matching happens in a fixed order, and the order explains most surprises.
The supported-version check comes before mapping. A request for version 3.0 never reaches your controller, even if a baseline such as "2.0+" would otherwise cover it. Baselines extend only across versions you declared as supported.
Which version wins
The table shows which method of AccountController runs for each header value, given the supported list 1.0, 1.1, 2.0.
| Request header | Version used | Handler |
|---|---|---|
| none | `1.0` (default) | `getV1` |
| `1.0` | `1.0` | `getV1` |
| `1.1` | `1.1` | none matches |
| `2.0` | `2.0` | `getV2` |
| `3.0` | rejected as unsupported | none, error |
The 1.1 row is the edge case to remember. Version 1.1 is supported, so it passes the supported check. But getV1 is a fixed "1.0" mapping and getV2 starts at 2.0. No handler claims 1.1, so the request fails. The failure is a version error, not a call to getV1. The chapter on error handling covers the exact responses.
Declaring 1.1 as supported is a promise that every endpoint answers it. You can keep that promise in two ways:
- Change
getV1toversion = "1.0+". Then it also serves1.1, andgetV2takes over from2.0. - Add a dedicated
version = "1.1"method for the endpoints that changed.
Baselines and specificity
A baseline can match many versions, so several methods can match one request. Suppose a controller has these methods:
@GetMapping(path = "/{id}", version = "1.0+")
public AccountV1 older(@PathVariable long id) {
return new AccountV1(id, "Ada Lovelace");
}
@GetMapping(path = "/{id}", version = "2.0+")
public AccountV2 newer(@PathVariable long id) {
return new AccountV2(id, "Ada", "Lovelace");
}A request for 2.0 matches both. Spring prefers the mapping whose version is closest to the request, which is the higher baseline. So newer handles 2.0, and older handles 1.0 and 1.1. You do not need to list exclusions.
This pattern fits the way most APIs evolve. Most endpoints do not change between versions. A baseline lets you write the endpoint once and add a new method only at the version where its behavior changes. A fixed version suits the opposite case, where you want a method pinned to one version and nothing else.
| Form | Example | Matches | Use when |
|---|---|---|---|
| Fixed | `"1.0"` | Only `1.0` | An endpoint existed only in one version, or you want explicit control |
| Baseline | `"1.0+"` | `1.0` and every later supported version | An endpoint is unchanged until a newer method takes over |
Versions on mappings without a version
A method without a version attribute has no version condition. It matches whatever version the request carries, if that version passes the supported check. It also competes with versioned methods on the same path, so mixing the two styles on one path is hard to reason about. Pick one style per path.
Unversioned endpoints are fine for operations that never change, such as /health style resources. For anything you expect to evolve, add a baseline such as "1.0+" from the start. That makes the first version explicit, and later versions are then a matter of adding a new method.
Common mistakes
- Declaring a version in the mapping but not as supported. The mapping refers to
2.0, but the supported list says1.0and1.1. Requests for2.0are rejected before they reach the controller. Keep the supported list and the mappings in step. - Using a fixed version where a baseline is needed.
getV2withversion = "2.0"works until you add2.1to the supported list. From then on,2.1has no handler. A baseline avoids this. - Duplicating a mapping. Two methods with the same path, HTTP method and identical
versionfail at startup with an ambiguous mapping error. This is a useful signal. Fix it by changing one version. - Assuming the default hides gaps. The default version is used only when the request carries no version. A client that sends
1.1does not fall back to the default. - Changing the path to carry the version and forgetting the mapping. If you switch to a path segment resolver, the version segment is read by the resolver. Do not also write
{version}into the@RequestMappingpath unless your configuration expects it.
Verifying the mapping
You can check the mappings from a test, using the header exactly as a client would. MockMvc is covered in detail in a later chapter. This short test confirms that 2.0 reaches getV2.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class AccountVersioningTests {
@Autowired
MockMvc mockMvc;
@Test
void version2ReturnsSplitName() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "2.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Ada"));
}
}Write one test per supported version for each versioned endpoint. The 1.1 gap above is the kind of problem such a test finds.
Summary
- The
versionattribute adds a version condition to a request mapping. - A fixed version such as
"1.0"matches only that version. A baseline such as"2.0+"matches that version and later supported ones. - The supported-version check runs before handler mapping, so unsupported versions never reach a controller.
- When several baselines match, the one closest to the request version wins.
- Every supported version needs a handler for every versioned path, or requests for that version fail.
Exercise
A service declares supported versions 1.0, 1.1, 2.0 and 2.1. Its controller has @GetMapping(path = "/{id}", version = "1.0") and @GetMapping(path = "/{id}", version = "2.0+") on the same path. Which of the four supported versions have no handler, and what is the smallest change that gives every supported version a handler?
Show answer
Versions 1.1 have no handler. The fixed "1.0" method matches only 1.0, and the "2.0+" baseline starts at 2.0, so it covers 2.0 and 2.1. The smallest change is to make the first method a baseline, version = "1.0+". Then 1.0 and 1.1 go to it, and 2.0 and 2.1 go to the "2.0+" method because it is the closest baseline.
Exercise
A request carries the header X-API-Version: 3.0, and the supported list is 1.0, 1.1, 2.0. A method is mapped with version = "2.0+". Does that method run? Explain why.
Show answer
No. The supported-version check happens before handler mapping, and 3.0 is not in the supported list, so the request is rejected as an invalid version. The baseline "2.0+" only extends across versions that are declared as supported. To serve 3.0, add it with addSupportedVersions and make sure a handler matches it.