Spring / Spring7 Intermediate to Advanced Interview questions
Why is @Order important when multiple Filters or HandlerInterceptors are registered in a Spring application?
Filters and interceptors frequently depend on state or side effects a previous one is expected to have already set up, so the sequence they run in isn't cosmetic - it's part of the application's correctness.
@Bean public FilterRegistrationBean<RequestLoggingFilter> loggingFilter() { FilterRegistrationBean<RequestLoggingFilter> reg = new FilterRegistrationBean<>(new RequestLoggingFilter()); reg.setOrder(1); // run early, before security decisions are made return reg; }
A few common examples: a CORS filter typically needs to run early enough to short-circuit preflight OPTIONS requests before an authentication filter has a chance to reject them for missing credentials the browser was never going to send on a preflight anyway; a request-logging filter usually wants to run before a security filter that might wrap or consume the request body; and a filter that opens a database transaction or a Hibernate session (the "open session in view" pattern) has to run before any interceptor or filter downstream that assumes an active session is available.
Without an explicit order - via @Order, implementing Ordered/PriorityOrdered, or setOrder() on a FilterRegistrationBean - Spring falls back to registration or classpath-discovery order, which is fragile: it can silently change when a dependency is upgraded, a new starter is added, or component scanning happens to discover classes in a different order, producing intermittent, hard-to-diagnose bugs where a filter's assumption about "what already ran" is quietly violated.
More Related questions...