Master Spring Boot Interceptors: Filters, Handlers, AOP, RestTemplate & Feign

This article explores the hierarchy of Spring Boot interception mechanisms—Filter, HandlerInterceptor, AOP, RestTemplate, Feign, and WebFilter—detailing their typical use cases, implementation code, pitfalls, and best‑practice ordering, while providing practical tips and performance monitoring advice for robust backend development.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master Spring Boot Interceptors: Filters, Handlers, AOP, RestTemplate & Feign

Introduction

Many developers write HandlerInterceptor for interception needs and get tangled in complex scenarios. This article uses a Liangshan (bandit) analogy to introduce six major Spring Boot interceptors.

1. Filter (Global Interceptor)

Filter is the chief of the bandits. Typical use: global authentication, request timing.

@WebFilter("/*")
public class CostFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        long start = System.currentTimeMillis();
        chain.doFilter(req, res); // release the request
        System.out.println("Interface cost:" + (System.currentTimeMillis() - start) + "ms");
    }
}

Note: Must be the highest level because it operates at the Servlet container layer. Using Spring beans inside a Filter requires WebApplicationContextUtils.

2. HandlerInterceptor (Second‑in‑Command)

HandlerInterceptor is the deputy. Typical use: permission verification, automatic request parameter binding.

public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("X-Token");
        if (!"vip666".equals(token)) {
            response.setStatus(403);
            return false; // block the request
        }
        return true;
    }
}

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthInterceptor())
                .addPathPatterns("/api/**")
                .excludePathPatterns("/api/login");
    }
}

Common pitfalls:

Modifying the response in postHandle after it has been committed (check response.isCommitted()).

Static resources must be excluded from interception (e.g., /exclude/**).

Interceptor order must be set correctly; lower order values execute earlier.

3. AOP Interceptor (Strategist)

AOP acts as the strategist. Typical use: service‑level caching and transaction management.

@Aspect
@Component
public class CacheAspect {
    @Around("@annotation(com.example.anno.Cacheable)")
    public Object aroundCache(ProceedingJoinPoint jp) throws Throwable {
        String cacheKey = buildKey(jp);
        Object cacheVal = redisTemplate.opsForValue().get(cacheKey);
        if (cacheVal != null) return cacheVal;
        Object result = jp.proceed();
        redisTemplate.opsForValue().set(cacheKey, result, 5, TimeUnit.MINUTES);
        return result;
    }
}

Tips:

Only Spring‑managed beans can be intercepted; objects created with new cannot.

AOP order should be greater than the transaction aspect.

Custom annotations work on interface methods; for class methods use @within.

4. RestTemplate Interceptor (Naval Commander)

RestTemplate interceptor is used for client‑side HTTP calls, e.g., adding headers or encrypting parameters.

public class TraceInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) {
        request.getHeaders().add("X-TraceId", UUID.randomUUID().toString());
        return execution.execute(request, body);
    }
}

@Bean
public RestTemplate restTemplate() {
    RestTemplate rt = new RestTemplate();
    rt.getInterceptors().add(new TraceInterceptor());
    return rt;
}

Gotchas:

If the body is a string, convert it to a byte array manually to avoid encoding issues.

Multiple interceptors execute in reverse order of registration (the first added runs last).

HTTPS calls require additional SSL configuration (e.g., SSLContext).

5. Feign Interceptor (Diplomat)

Feign interceptor handles declarative client calls, adding signatures or headers.

public class FeignAuthInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        template.header("Authorization", "Bearer " + SecurityContext.getToken());
    }
}

@Configuration
public class FeignConfig {
    @Bean
    public FeignAuthInterceptor feignAuthInterceptor() {
        return new FeignAuthInterceptor();
    }
}

Issues:

GET request bodies are dropped; custom handling is required.

Form parameters need manual encoding (use feign‑form extension).

Path variables require @Param and expression parsing for dynamic values.

6. WebFilter (Special Forces)

WebFilter works in a WebFlux reactive pipeline, e.g., handling CORS.

@Component
public class CorsWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        return chain.filter(exchange);
    }
}

Requirements:

Effective only in a WebFlux environment; not applicable to traditional MVC.

Uses reactive programming model (functional style).

Non‑blocking pipeline; must work with Mono/Flux.

Best Practices

Order Matters

Filter → HandlerInterceptor → AOP; earlier interception saves effort, but avoid business logic in Filters.

Choose the Right Tool

Simple authentication: HandlerInterceptor.

Method‑level control: AOP.

Microservice communication: Feign interceptor.

Monitor Performance

Use Arthas to monitor interceptor latency and avoid chain overhead.

# View HandlerInterceptor latency
trace *.preHandle ' #cost>10 '

# Diagnose AOP aspect
watch com.example.aop.*Aspect * '{params,returnObj}' -x 3
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaaopSpring BootfeignInterceptorresttemplate
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.