0 day streak
java / expert
Snippet

Custom RequestCondition for Semantic API Versioning

Custom RequestConditions allow for sophisticated request mapping logic that goes beyond standard URL or param matching. By implementing this interface, you can route requests to specific controller methods based on custom headers, media types, or even complex business logic like feature flags.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {
private final String version;
@Override
public ApiVersionCondition getMatchingCondition(HttpServletRequest request) {
String header = request.getHeader("X-API-Version");
return version.equals(header) ? this : null;
}
@Override
public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
return other.version.compareTo(this.version);
}
// combine and other methods omitted
}
spring
Breakdown
1
public class ApiVersionCondition implements RequestCondition<ApiVersionCondition>
Defines a contract for Spring's HandlerMapping to evaluate custom matching logic.
2
return version.equals(header) ? this : null;
Returns this condition if the request matches the specified criteria, otherwise null.
3
return other.version.compareTo(this.version);
Determines which mapping takes precedence when multiple methods match the request.