Prefer mapping without version for unversioned request

Closes gh-35237
This commit is contained in:
rstoyanchev 2025-07-28 06:26:29 +01:00
parent 48506db996
commit 2238121350
4 changed files with 26 additions and 2 deletions

View File

@ -128,7 +128,9 @@ public final class VersionRequestCondition extends AbstractRequestCondition<Vers
return (-1 * compareVersions(this.version, otherVersion));
}
else {
return (this.version != null ? -1 : 1);
// Prefer mapping without version for unversioned request
Comparable<?> version = exchange.getAttribute(HandlerMapping.API_VERSION_ATTRIBUTE);
return (version != null ? (this.version != null ? -1 : 1) : (this.version != null ? 1 : -1));
}
}

View File

@ -18,6 +18,7 @@ package org.springframework.web.reactive.result.condition;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
@ -159,6 +160,15 @@ public class VersionRequestConditionTests {
condition.handleMatch(exchange);
}
@Test
void compareWithoutRequestVersion() {
VersionRequestCondition condition = Stream.of(condition("1.1"), condition("1.2"), emptyCondition())
.min((c1, c2) -> c1.compareTo(c2, exchange()))
.get();
assertThat(condition).isEqualTo(emptyCondition());
}
private VersionRequestCondition condition(String v) {
this.strategy.addSupportedVersion(v.endsWith("+") ? v.substring(0, v.length() - 1) : v);
return new VersionRequestCondition(v, this.strategy);

View File

@ -127,7 +127,9 @@ public final class VersionRequestCondition extends AbstractRequestCondition<Vers
return (-1 * compareVersions(this.version, otherVersion));
}
else {
return (this.version != null ? -1 : 1);
// Prefer mapping without version for unversioned request
Comparable<?> version = (Comparable<?>) request.getAttribute(HandlerMapping.API_VERSION_ATTRIBUTE);
return (version != null ? (this.version != null ? -1 : 1) : (this.version != null ? 1 : -1));
}
}

View File

@ -18,6 +18,7 @@ package org.springframework.web.servlet.mvc.condition;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
@ -146,6 +147,15 @@ public class VersionRequestConditionTests {
assertThat(list.get(0)).isEqualTo(condition(expected));
}
@Test
void compareWithoutRequestVersion() {
VersionRequestCondition condition = Stream.of(condition("1.1"), condition("1.2"), emptyCondition())
.min((c1, c2) -> c1.compareTo(c2, new MockHttpServletRequest()))
.get();
assertThat(condition).isEqualTo(emptyCondition());
}
@Test // gh-35236
void noRequestVersion() {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/path");