Feature/allowed method interceptor #35273
Open
+872
−20
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Support HTTP method-restricted interceptors in
InterceptorRegistration
This PR implements #35272, adding support for restricting
HandlerInterceptor
registration to specific HTTP methods.Motivation
Spring MVC currently allows interceptors to be applied based on path patterns, but not HTTP methods. When method-based filtering is needed, it must be manually implemented within the interceptor itself:
This approach clutters interceptor logic with method checks and duplicates similar logic across interceptors when needed. Centralizing HTTP method filtering in the registration API provides a cleaner and more declarative configuration style.
Solution
This PR introduces a new method to
InterceptorRegistration
:This allows restricting the interceptor to specific HTTP methods like
GET
,POST
, etc. Under the hood, the framework wraps the givenHandlerInterceptor
in a newMethodInterceptor
that delegates calls only when the request's HTTP method matches one of the allowed methods.The interceptor will now be invoked only for POST and PUT requests matching
/api/**
.Implementation Details
InterceptorRegistration
stores allowed HTTP methods as aSet<String>
.MethodInterceptor
.MethodInterceptor
checks the request's method before delegating to the original interceptor.Tests
A dedicated test class
MethodInterceptorTests
is included to validate:preHandle
,postHandle
,afterCompletion
) are covered.Example
In this example,
AuditInterceptor
will apply only forGET
requests under/admin/**
.Compatibility
MappedInterceptor
,HandlerInterceptor
) without exposing new public types.