HandlerInterceptor vs HandlerInterceptorAdapter

We can create create custom interceptors in spring by either implementing HandlerInterceptor (Recommended by Spring) or by extending abstract class HandlerInterceptorAdapter.

Why Spring framework provides two options?

Approach-I:

HandlerInterceptor If our custom class implementing HandlerInterceptor interface,then we will have to provide implementation to 3 abstract methods preHandle(), postHandle and afterCompletion().

Problem with this approach is, just assume a scenario when you just need to provide implementation to only one method and there is no need to provide implementation to remaining 2 methods. Unfortunetly, we will have to provide empty implementation to other 2 methods.This approach will be boilerplate for the application code as we are providing empty implemetations to 2 methods.

public class CustomHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        // Some complex logic

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,Object handler, ModelAndView modelAndView) throws Exception {
      
      // empty

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) throws Exception {
       
       //empty

    }
}

Approach-II:

HandlerInterceptorAdapter To solve the above problem, spring framework provides one more abstract class HandlerInterceptorAdapter which already contains empty implementation of above 3 methods and custom interceptor class can simply override them based on requirement.

public class CustomHandlerInterceptor extends HandlerInterceptorAdapter {

@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //Some complex logic } }

NOTE :HandlerInterceptorAdapter is deprecated in Spring 5.3+. Spring community recommends to use HandlerInterceptor from Spring 5.3+. Java 8+ allows interfaces to have default implementations that's why spring has deprecated HandlerInterceptorAdapter in Spring 5.3+