Sub topic 5
Declaring supported versions and how versions are parsed
This chapter assumes you can build Spring MVC controllers and have read the earlier chapters of this tutorial. You should know how ApiVersionConfigurer enables versioning and how a version resolver extracts a raw string from the request. Here you will see what happens to that string next. Spring turns it into a comparable object, checks it against a set of supported versions, and only then matches it to a controller method.
Two jobs: parsing and validating
A version resolver returns plain text such as "2.0" or "1". Spring cannot compare text in a meaningful way, because "1.10" sorts before "1.9" as a string. Two collaborators fix this:
- The version parser converts the raw text into a
Comparablevalue. The same parser is used for the request version, for the versions you declare as supported, and for theversionattribute on mappings. - The set of supported versions is the list of versions the application accepts. A request whose parsed version is not in this set is rejected before any controller runs.
Because everything is parsed with one parser, "1", "1.0" and "1.0.0" are the same version by default. The parser also gives the versions an order. That order is what makes baseline mappings such as "1.1+" work, which a later chapter covers.
Declaring supported versions
You declare supported versions on the configurer with addSupportedVersions. Each argument is a string that goes through the version parser.
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");
}
}With this configuration, a request carrying X-API-Version: 1.1 is accepted. A request carrying X-API-Version: 3.0 is rejected with a client error, even if a controller method happens to declare 3.0. A request carrying X-API-Version: 1 is accepted, because the default parser reads it as 1.0.0, which equals the declared 1.0.
The Spring Boot property equivalent is a comma-separated list:
spring.mvc.apiversion.use.header=X-API-Version
spring.mvc.apiversion.supported=1.0,1.1,2.0
spring.mvc.apiversion.default=1.0Detected versions
Spring can also collect versions from your controllers. When a mapping declares version = "2.0", that version can be added to the supported set automatically. This behavior is controlled by detectSupportedVersions, which is enabled by default.
Detection is convenient, but it ties your public contract to whatever annotations exist in the code. A typo such as version = "2.O" would silently create a new supported version, or fail at parse time, depending on the text. For a public API, prefer an explicit list and turn detection off:
configurer.useRequestHeader("X-API-Version")
.addSupportedVersions("1.0", "1.1", "2.0")
.detectSupportedVersions(false);With detection off, the supported set contains exactly what you listed. If a controller declares a version that is not in the set, no request can reach it. That makes mistakes visible in testing instead of in production.
How the default parser reads versions
The default parser is a semantic version parser. It accepts up to three numeric parts separated by dots: major, major.minor or major.minor.patch. Missing parts count as zero. Each part is an integer, and versions compare part by part.
| Input | Parsed as | Notes |
|---|---|---|
| `1` | 1.0.0 | Same version as `1.0` |
| `1.1` | 1.1.0 | |
| `1.10` | 1.10.0 | Newer than `1.9`, unlike a string comparison |
| `2.0.3` | 2.0.3 | Patch part is kept for ordering |
| `v2` | fails | A prefix is not numeric, so parsing is rejected |
| `2.x` | fails | Non-numeric part |
| `1.2.3.4` | fails | Too many parts |
A value that cannot be parsed is treated as an invalid version and the request gets a client error response (400). The error is raised before handler matching. The next chapters cover the exact error types and how to customize them.
Most real APIs only publish major.minor versions. The default parser accepts that, so you rarely need to change it. Change it when the version text on the wire has a format the default parser rejects, for example a v prefix or a date.
Writing a custom parser
A custom parser implements ApiVersionParser<V>, where V is a Comparable type. It has one method, parseVersion, which takes the raw string and returns the comparable value. This example accepts an optional v prefix and uses plain integers as versions, so v2 and 2 are the same version:
import org.springframework.web.accept.ApiVersionParser;
public class MajorOnlyVersionParser implements ApiVersionParser<Integer> {
@Override
public Integer parseVersion(String version) {
String number = version.startsWith("v") || version.startsWith("V")
? version.substring(1)
: version;
try {
return Integer.valueOf(number);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException("Not a major version: " + version, ex);
}
}
}Register it on the configurer:
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 MajorVersionConfig implements WebMvcConfigurer {
@Override
public void configureApiVersioning(ApiVersionConfigurer configurer) {
configurer.useRequestHeader("X-API-Version")
.setVersionParser(new MajorOnlyVersionParser())
.addSupportedVersions("1", "2", "3")
.setDefaultVersion("1");
}
}Several points about this setup:
- The supported versions
"1","2"and"3"are parsed by your parser, so they become the integers 1, 2 and 3. - Mappings such as
version = "2"andversion = "2+"use the same parser. - A request with
X-API-Version: v2and one withX-API-Version: 2both resolve to 2. - A request with
X-API-Version: 2.1fails to parse, becauseInteger.valueOf("2.1")throws. Your parser decides what counts as valid.
Failure modes and gotchas
- Equivalent strings. Because
"1"and"1.0"parse to the same value, you cannot treat them as different versions. If you list both inaddSupportedVersions, the set still has one entry. - Parser exceptions. Throw an
IllegalArgumentExceptionwith a clear message from a custom parser. Spring reports it as an invalid version rather than a server error. Do not returnnull. - Ordering assumptions. Baseline mappings depend on the parsed order. A parser whose
Comparableordering does not match your idea of "newer" will make2+select the wrong methods. - Case and whitespace. The default parser does not trim or normalize text. If clients may send padded values, handle that in a custom parser or in a custom resolver.
- Detection drift. With detection on, adding
version = "2.5"to a controller can change the supported set without any configuration edit. Review annotations as part of API review, or turn detection off. - Property and Java configuration together. Both set up the same strategy. Pick one place per application so the supported list has a single source of truth.
Choosing between explicit and detected versions
| Concern | Explicit list, detection off | Detection on |
|---|---|---|
| Public contract visible in one place | Yes | No, spread across controllers |
| Typo in a mapping | Handler unreachable, caught by tests | New version may become accepted |
| Effort when adding a version | Edit config and controller | Edit controller only |
| Good fit | Public or partner APIs | Internal APIs with few consumers |
Exercise
An application uses the default parser and declares addSupportedVersions("1.0", "2.0") with detection turned off. What happens for requests carrying X-API-Version: 1, X-API-Version: 1.5 and X-API-Version: v2? Explain each outcome.
Show answer
1 is parsed as 1.0.0, which equals the declared 1.0, so the request is accepted. 1.5 parses to 1.5.0, but it is not in the supported set, so it is rejected as an unsupported version with a client error. v2 cannot be parsed by the default parser because of the v prefix, so it is rejected as an invalid version before the supported check. To accept v2, you would supply a custom ApiVersionParser.
Exercise
Write a custom parser and configuration so that clients can send X-API-Version: 2025-06, where later months are newer versions. Which type could the parser return, and what must you also change in the supported list?
Show answer
Return java.time.YearMonth, which is Comparable, using YearMonth.parse(version) and wrapping a DateTimeParseException in an IllegalArgumentException. Register it with setVersionParser, and write the supported versions in the same format, for example addSupportedVersions("2025-01", "2025-06"). Mapping attributes such as version = "2025-06" must use that format too, because they go through the same parser.