Sub topic 9
Configuring versioning with Spring Boot properties
Earlier chapters configured versioning in Java with ApiVersionConfigurer. This chapter moves the same setup into application.properties or application.yml. It assumes you can write a Spring MVC controller and that you know how @GetMapping(version = ...) selects a handler. It also assumes you know which request header, path segment, query parameter or media type parameter your API will use to carry the version.
Why use properties instead of a configurer
Spring Boot 4 reads a group of spring.mvc.apiversion.* properties and applies them to the same ApiVersionConfigurer you would otherwise call yourself. For the common case, one resolver plus a list of supported versions plus an optional default, the properties are shorter than a @Configuration class. They also bring the usual Boot benefits:
- You can override them per profile, for example a looser default in
dev. - You can override them with environment variables or command-line arguments, without a rebuild.
- You can override them in a single test with
@SpringBootTest(properties = ...).
A configurer is still the right tool when you need logic, such as a custom ApiVersionParser, a custom resolver, or deprecation handling. Properties cover only the declarative settings.
The minimal setup
This is the header-based configuration from the Java example, expressed as properties:
spring.mvc.apiversion.use.header=X-API-Version
spring.mvc.apiversion.supported=1.0,1.1,2.0
spring.mvc.apiversion.default=1.0The three lines do the following:
use.headerregisters a resolver that reads the version from theX-API-Versionrequest header.supportedlists the versions the application accepts. Anything else is rejected.defaultnames the version to assume when the request carries none.
The same configuration in YAML:
spring:
mvc:
apiversion:
use:
header: X-API-Version
supported:
- "1.0"
- "1.1"
- "2.0"
default: "1.0"Quote the version strings in YAML. Without quotes, 1.0 is read as the number 1, which becomes 1 and no longer matches the text you wrote in version = "1.0".
The property reference
The table lists the properties you will use most. Check the Spring Boot reference for your exact 4.x release, since the set of options can grow between minor versions.
| Property | Purpose |
|---|---|
| `spring.mvc.apiversion.use.header` | Read the version from the named request header. |
| `spring.mvc.apiversion.use.path-segment` | Read the version from the path segment at the given index. |
| `spring.mvc.apiversion.use.query-parameter` | Read the version from the named query parameter. |
| `spring.mvc.apiversion.use.media-type-parameter` | Read the version from a parameter on the given media type. |
| `spring.mvc.apiversion.supported` | Comma-separated list of accepted versions. |
| `spring.mvc.apiversion.default` | Version assumed when a request has none. |
WebFlux applications use the same names under spring.webflux.apiversion.*. Apart from the prefix, nothing changes.
Pick one use.* property. A single API normally takes its version from one place. Mixing sources makes it unclear which value wins when a client sends two.
What the properties produce
Take the controller from the previous chapter. It maps "1.0" to one method and "2.0+" to another. With the properties above, the application behaves as follows:
| Request header | Result |
|---|---|
| none | Version 1.0 is assumed, so `getV1` runs. |
| `X-API-Version: 1.0` | `getV1` runs. |
| `X-API-Version: 2.0` | `getV2` runs. |
| `X-API-Version: 3.0` | Rejected as unsupported. |
The diagram shows the decision order for one request:
Default and required interact
The default property affects more than the missing-header case. A request is only required to carry a version when no default exists. If you set default, a missing version is never an error, because Spring substitutes the default.
If you remove the default line, a request without the header fails with a client error (HTTP 400). The cause is a MissingApiVersionException. If you keep the default, old clients that predate versioning keep working. That is the usual reason to set it. Pin the default to the oldest version you still support, not to the newest. Otherwise an unversioned client is silently moved to your latest behavior the day you release it.
A request that names a version missing from the supported list also fails with HTTP 400. Here the cause is an InvalidApiVersionException. A version you did not declare fails at once instead of falling through to some handler.
Keeping the supported list in sync
The supported list is configuration, but it also depends on your code. Every version a controller mentions should appear in the list, and every listed version should have a handler that can answer it. Consider this pairing:
@GetMapping(path = "/{id}", version = "1.0")
public AccountV1 getV1(@PathVariable long id) { /* ... */ }
@GetMapping(path = "/{id}", version = "2.0+")
public AccountV2 getV2(@PathVariable long id) { /* ... */ }If supported is 1.0,2.0, every listed version has a handler. Add 1.1 to the list and a client sending 1.1 is accepted by the supported check but matches no fixed-version handler. "2.0+" covers only 2.0 and later, and "1.0" covers only 1.0. So when you add a version to the properties, add or widen a mapping in the same change.
Overriding properties in tests
Because the properties live in the environment, a test can set exactly what it needs. This test pins the configuration and checks all three outcomes: default, explicit version, and unsupported version.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
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(properties = {
"spring.mvc.apiversion.use.header=X-API-Version",
"spring.mvc.apiversion.supported=1.0,2.0",
"spring.mvc.apiversion.default=1.0"
})
@AutoConfigureMockMvc
class VersionPropertiesTests {
@Autowired
MockMvc mockMvc;
@Test
void missingVersionFallsBackToDefault() throws Exception {
mockMvc.perform(get("/accounts/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Ada Lovelace"));
}
@Test
void explicitVersionSelectsNewHandler() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "2.0"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.firstName").value("Ada"));
}
@Test
void unsupportedVersionIsRejected() throws Exception {
mockMvc.perform(get("/accounts/1").header("X-API-Version", "3.0"))
.andExpect(status().isBadRequest());
}
}The first test asserts $.name, which only the version 1.0 record has. That confirms the default was applied and not merely that some handler ran.
Combining properties with a configurer
You can define a WebMvcConfigurer that implements configureApiVersioning while the properties are also set. Both then act on the same configuration, and the outcome depends on which call runs last. That is hard to read and hard to debug. Choose one approach per application:
- Use properties when you only need a resolver, a supported list and a default.
- Use a configurer when you need anything the properties cannot express.
If you outgrow the properties, move all of the settings into the configurer in one commit and delete the property lines. Don't leave a half-and-half setup.
Common errors
- Unquoted YAML versions.
1.0becomes a number and no longer matches"1.0". Quote every version. - A missing
supportedlist. Without it, the set of valid versions is not defined by your configuration, so typos in the header are not caught at the edge. Always declare it. - A default pointing at the newest version. Unversioned clients change behavior on each release.
- Property names with the wrong prefix. Servlet applications use
spring.mvc.*. Reactive applications usespring.webflux.*. A misplaced prefix is ignored, and the application starts with no versioning. - Relying on a property that your Boot version lacks. Boot ignores unknown
spring.*keys. Addspring-boot-configuration-processormetadata checks or look at the IDE's property autocomplete to catch this early.
Environment overrides
Boot's relaxed binding lets you set the same values outside the file. For a container deployment you might write:
SPRING_MVC_APIVERSION_USE_HEADER=X-API-Version
SPRING_MVC_APIVERSION_SUPPORTED=1.0,2.0
SPRING_MVC_APIVERSION_DEFAULT=1.0Use this to retire a version without a code change. Removing 1.0 from SPRING_MVC_APIVERSION_SUPPORTED makes those requests fail with HTTP 400 at the next restart, even though the "1.0" handler still exists in the code.
Exercise
A service sets spring.mvc.apiversion.use.header=X-API-Version, spring.mvc.apiversion.supported=1.0,2.0, and no default. A client sends a request with no X-API-Version header. What happens, and what single property change makes the request succeed against version 1.0?
Show answer
The request fails with a client error (HTTP 400), because no default exists and a version is therefore required. Adding spring.mvc.apiversion.default=1.0 makes Spring assume version 1.0, so the version 1.0 handler answers the request.
Exercise
A YAML file contains supported: [1.0, 2.0] and a controller uses version = "1.0". Requests with X-API-Version: 1.0 do not behave as expected. What is the likely cause and the fix?
Show answer
YAML reads the unquoted 1.0 as a number, so the supported value is 1 and no longer matches the text "1.0". Quote the values, for example supported: ["1.0", "2.0"].