Understanding Filters, Interceptors, and AOP in Spring Boot: When and How They Run

This article explains the concepts, lifecycle methods, and configuration of Spring Boot's Filter, Interceptor, and AOP mechanisms, compares their execution order, and shows code examples to help developers choose the right technique for adding cross‑cutting functionality without altering core business logic.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Understanding Filters, Interceptors, and AOP in Spring Boot: When and How They Run

In daily development, Filter, Interceptor, and AOP are three common request‑handling techniques in Java Spring that can add extra functionality without affecting the main business logic.

Filter

What is a Filter

Filter

is part of the Java Servlet specification defined in the javax.servlet package. It can pre‑process or post‑process all HTTP requests ( HttpServletRequest) and responses ( HttpServletResponse) handled by the servlet container, for example performing authentication before the request reaches the target resource or modifying the response before it is sent to the client.

Filter Interface

package javax.servlet;

import java.io.IOException;

public interface Filter {
    default public void init(FilterConfig filterConfig) throws ServletException {}
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
    default public void destroy() {}
}

Custom filters must implement this interface. The three lifecycle methods are: init() – called once when the web container starts and creates the filter instance. doFilter() – the core method executed for every request. destroy() – called once when the container shuts down to release resources.

Filter Configuration in Spring Boot

Spring Boot supports several registration methods:

Use @WebFilter together with @ServletComponentScan annotations.

Register a FilterRegistrationBean bean.

Declare the filter as a Spring @Component.

@WebFilter(urlPatterns = "/*", filterName = "exampleFilter")
public class ExampleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // pass to next filter or target
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {}
}
@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean<ExampleFilter> customFilterRegistration() {
        FilterRegistrationBean<ExampleFilter> registrationBean = new FilterRegistrationBean<>();
        ExampleFilter customFilter = new ExampleFilter();
        registrationBean.setFilter(customFilter);
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        registrationBean.addInitParameter("encoding", "UTF-8");
        return registrationBean;
    }
}
@Component
public class ExampleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {}
}

Interceptor

What is an Interceptor

Interceptor

is part of Spring MVC (package org.springframework.web.servlet) and implements the HandlerInterceptor interface. Unlike Filter, it does not depend on the servlet container and is specific to Spring.

HandlerInterceptor Interface

/**
 * A HandlerInterceptor gets called before the appropriate HandlerAdapter triggers the execution of the handler itself.
 * This mechanism can be used for a large field of preprocessing aspects, e.g. for authorization checks,
 * or common handler behavior like locale or theme changes.
 */
public interface HandlerInterceptor {
    default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
    default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {}
    default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {}
}

Key methods: preHandle – executed before the controller method; returning false aborts the interceptor chain. postHandle – executed after the controller method but before view rendering; runs in reverse order. afterCompletion – executed after the complete request, typically for cleanup.

Interceptor Configuration

Implement HandlerInterceptor and register it via WebMvcConfigurer:

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor preHandle: " + request.getRequestURI());
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor postHandle: " + request.getRequestURI());
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor afterCompletion: " + request.getRequestURI());
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/static/**", "/login", "/register");
    }
}

AOP (Aspect‑Oriented Programming)

What is AOP

AOP is a programming paradigm that separates cross‑cutting concerns (such as transaction management or logging) from core business logic. Spring AOP provides an implementation of this paradigm.

Core Concepts

Aspect – a modular class containing advice and pointcuts.

Advice – action taken at a particular join point (e.g., @Before, @AfterReturning, @Around, etc.).

Join Point – a point during program execution, such as a method call.

Pointcut – expression that matches join points.

Introduction – adds new methods or fields to existing classes.

Target Object – the object being advised.

Proxy – the object created by the AOP framework to weave advice (JDK dynamic proxy or CGLIB).

Spring AOP Configuration

Steps:

Enable AOP with @EnableAspectJAutoProxy on a configuration class.

Define an aspect class annotated with @Aspect and @Component.

Declare pointcuts using @Pointcut and AspectJ expressions.

Define advice methods ( @Before, @AfterReturning, @AfterThrowing, @Around, @After).

@SpringBootApplication
@EnableAspectJAutoProxy
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}
@Aspect
@Component
public class AllAdviceAspect {
    @Pointcut("execution(* com.example.service..*.*(..))")
    public void serviceLayerExecution() {}

    @Before("serviceLayerExecution()")
    public void logBefore(JoinPoint joinPoint) {
        log.info("Before method execution: {}", joinPoint.getSignature().getName());
    }

    @AfterReturning(pointcut = "serviceLayerExecution()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        log.info("Method returned successfully: {}, Result: {}", joinPoint.getSignature().getName(), result);
    }

    @AfterThrowing(pointcut = "serviceLayerExecution()", throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Exception ex) {
        log.error("An exception was thrown in {}: {}", joinPoint.getSignature().getName(), ex.getMessage());
    }

    @After("serviceLayerExecution()")
    public void logAfter(JoinPoint joinPoint) {
        log.info("After method execution: {}", joinPoint.getSignature().getName());
    }

    @Around("serviceLayerExecution()")
    public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
        log.info("Starting around advice for method: {}", pjp.getSignature().getName());
        long start = System.currentTimeMillis();
        try {
            Object result = pjp.proceed();
            log.info("Method {} took {} ms to execute", pjp.getSignature().getName(), System.currentTimeMillis() - start);
            return result;
        } catch (Throwable e) {
            log.error("Error during method execution: {}", e.getMessage());
            throw e;
        } finally {
            log.info("Ending around advice for method: {}", pjp.getSignature().getName());
        }
    }
}

Comparison

Filter

is part of the Java Servlet specification and works at the servlet container level, affecting every HTTP request. Interceptor is a Spring MVC mechanism that runs after the servlet container has dispatched the request to DispatcherServlet but before the controller handler is invoked.

Spring AOP operates on specific join points (typically controller methods) after interceptors have run, allowing fine‑grained cross‑cutting logic.

This article, based on Spring Boot, introduced Filters, Interceptors, and Spring AOP, explained their basic concepts, lifecycle, configuration, and execution order, and showed that both Filters and Interceptors can be viewed as concrete implementations of the AOP idea, each operating at a different layer.

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 BootInterceptorfilter
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.