title: advise controller method *before* @Valid annotation is handled
body: <p>I am adding rate-limiting to a restful webservice using Spring MVC 4.1.</p>
  
  <p>I created a <code>@RateLimited</code> annotation that I can apply to controller methods.  A Spring AOP aspect intercepts calls to these methods and throws an exception if there have been too many requests:</p>
  
  <pre><code>@Aspect
  @Component
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public class RateLimitingAspect {
  
      @Autowired
      private RateLimitService rateLimitService;
  
      @Before("execution(* com.example..*.*(.., javax.servlet.ServletRequest+, ..)) " +
              "&amp;&amp; @annotation(com.example.RateLimited)")
      public void wait(JoinPoint jp) throws Throwable {
  
          ServletRequest request =
              Arrays
                  .stream(jp.getArgs())
                  .filter(Objects::nonNull)
                  .filter(arg -&gt; ServletRequest.class.isAssignableFrom(arg.getClass()))
                  .map(ServletRequest.class::cast)
                  .findFirst()
                  .get();
          String ip = request.getRemoteAddr();
          int secondsToWait = rateLimitService.secondsUntilNextAllowedAttempt(ip);
          if (secondsToWait &gt; 0) {
            throw new TooManyRequestsException(secondsToWait);
          }
      }
  </code></pre>
  
  <p>This all works perfectly, except when the <code>@RateLimited</code> controller method has parameters marked as <code>@Valid</code>, e.g.:</p>
  
  <pre><code>@RateLimited
  @RequestMapping(method = RequestMethod.POST)
  public HttpEntity&lt;?&gt; createAccount(
                             HttpServletRequest request,
                             @Valid @RequestBody CreateAccountRequestDto dto) {
  
  ...
  }
  </code></pre>
  
  <p>The problem: if validation fails, the validator throws <code>MethodArgumentNotValidException</code>, which is handled by an <code>@ExceptionHandler</code>, which returns an error response to the client, never triggering my <code>@Before</code> and therefore bypassing the rate-limiting.</p>
  
  <p><strong>How can I intercept a web request like this in a way that takes precedence over parameter validation?</strong></p>
  
  <p>I've thought of using Spring Interceptors or plain servlet Filters, but they are mapped by simple url-patterns and I need to differentiate by GET/POST/PUT/etc.</p>