Custom Interceptors
Building and registering custom HandlerInterceptors with WebMvcConfigurer
- Register multiple interceptors with addPathPatterns and excludePathPatterns
- Build an auth token interceptor using preHandle
- Attach request metadata for logging with afterCompletion
Handler Interceptors Custom Annotations AOP-Based Method Interceptors
@Component, @Autowired)
- AOP (Aspect-Oriented Programming) in Spring — pointcuts, advice, join points, @Around, @Aspect
- Java Annotations — how annotations work, meta-annotations
If AOP or Annotations are unfamiliar, study those topics first. This guide will reference them directly.Table of Contents
- What Is an Interceptor?
- Where Interceptors Fit in the Spring Request Lifecycle
- Type 1 — Handler Interceptor (Before Controller)
- Custom Annotations — Foundation for Method-Level Interceptors
- Meta-Annotations —
@Targetand@Retention - Passing Data Through Annotations (Annotation Fields)
- Type 2 — AOP-Based Method Interceptor (After Controller, Around a Method)
- Comparison — Handler Interceptor vs AOP Interceptor
- Summary & Quick Reference
- Interview Notes
- Practice Questions
1. What Is an Interceptor?
Definition
An interceptor is a mediator component that gets invoked before or after your actual code executes, without modifying the original code itself.
Think of it like a security checkpoint at an airport — every passenger (request) passes through it before reaching their gate (controller/method), regardless of where they are going.
Why Interceptors Exist
Without interceptors, cross-cutting concerns (things that apply to many methods/classes) would have to be manually written in every method. Examples:
- Logging every request
- Checking authentication on every API
- Starting/stopping a cache
- Measuring execution time
Interceptors allow you to write this logic once in a centralized place, and have it applied automatically wherever needed.
Real-World Analogy
A hotel concierge (interceptor) greets every guest (request) before they reach their room (controller). The guest doesn't need to know the concierge exists — the concierge operates transparently.
2. Where Interceptors Fit in the Spring Request Lifecycle
When an HTTP request arrives at a Spring Boot application, it travels through several layers:
Two Interception Points
| Interception Point | Mechanism | When It Runs |
|---|---|---|
| Before the Controller | HandlerInterceptor | After DispatcherServlet picks the controller, before the controller method executes |
| Around a specific method | AOP (@Aspect, @Around) | When a method annotated with a custom annotation is invoked, anywhere in the application |
3. Type 1 Handler Interceptor (Before Controller)
Overview
HandlerInterceptor is a Spring interface that lets you intercept HTTP requests at the dispatcher servlet level — after routing is resolved but before (and after) the controller executes.
Use Cases
- Authentication / Authorization checks
- Request logging
- Rate limiting
- Adding common response headers
Step 1 Create the Custom Interceptor Class
Implement the HandlerInterceptor interface:
1@Component2public class MyCustomInterceptor implements HandlerInterceptor {3
4 @Override5 public boolean preHandle(HttpServletRequest request,6 HttpServletResponse response,7 Object handler) throws Exception {8 // Runs BEFORE the controller method9 System.out.println("PRE HANDLE — request intercepted before controller");10 // Return true to continue the request chain11 // Return false to block the request (e.g., auth failed)12 return true;13 }14
15 @Override16 public void postHandle(HttpServletRequest request,17 HttpServletResponse response,18 Object handler,19 ModelAndView modelAndView) throws Exception {20 // Runs AFTER the controller method — only if no exception occurred21 System.out.println("POST HANDLE — controller executed successfully");22 }23
24 @Override25 public void afterCompletion(HttpServletRequest request,26 HttpServletResponse response,27 Object handler,28 Exception ex) throws Exception {29 // Runs AFTER everything — even if an exception occurred30 // Similar to a finally block in Java31 System.out.println("AFTER COMPLETION — runs always, success or exception");32 }33}◆ The Three Methods Explained
| Method | When It Runs | Exception Behavior | Analogy |
|---|---|---|---|
preHandle() | Before controller | Runs before anything | Security checkpoint before entry |
postHandle() | After controller, before response sent | Skipped if exception thrown | Receptionist after a successful meeting |
afterCompletion() | After response is complete | Always runs, even on exception | finally block — guaranteed cleanup |
preHandle() returns a boolean:
- true → allow the request to proceed to the controller
- false → block the request immediately (no controller invoked, no further interceptors)afterCompletion behaves like a finally block — use it for resource cleanup (closing connections, clearing thread-locals, etc.) that must happen regardless of success or failure.Step 2 Register the Interceptor in Configuration
Simply creating the interceptor class is not enough. You must register it and specify which URL paths it applies to.
1@Configuration2public class AppConfig implements WebMvcConfigurer {3
4 @Autowired5 private MyCustomInterceptor myCustomInterceptor;6 // @Autowired works because @Component is on MyCustomInterceptor7
8 @Override9 public void addInterceptors(InterceptorRegistry registry) {10 registry.addInterceptor(myCustomInterceptor)11 .addPathPatterns("/api/*") // Apply to all /api/* paths12 .excludePathPatterns( // Exclude specific paths13 "/api/update-user",14 "/api/delete-user"15 );16 }17}◆ Configuration Breakdown
| Configuration Call | Purpose |
|---|---|
addInterceptor(interceptor) | Register which interceptor to use |
addPathPatterns("/api/*") | Comma-separated patterns where interceptor applies. * is a wildcard |
excludePathPatterns(...) | Specific paths to exclude from interception |
@Component vs @Bean:
- If your interceptor has @Component, Spring creates the bean automatically → inject with @Autowired.
- Without @Component, declare it manually in AppConfig:
``java
registry.addInterceptor(new MyCustomInterceptor());
``How `DispatcherServlet` Triggers the Interceptor Internally
Inside DispatcherServlet.doDispatch(), Spring executes this sequence:
11. applyPreHandle() → calls preHandle() on all matched interceptors22. handle() → your actual controller method executes33. applyPostHandle() → calls postHandle() on all matched interceptors (only on success)44. afterCompletion() → always called in the finally blockThis means Spring's own source code confirms the same flow described above.
Full Execution Flow Handler Interceptor
Complete Example Handler Interceptor
Controller:
1@RestController2public class UserController {3
4 @GetMapping("/api/get-user")5 public String getUser() {6 System.out.println("CONTROLLER — getUser() executing");7 return "User fetched successfully";8 }9}Interceptor:
1@Component2public class MyCustomInterceptor implements HandlerInterceptor {3
4 @Override5 public boolean preHandle(HttpServletRequest request,6 HttpServletResponse response,7 Object handler) {8 System.out.println("PRE HANDLE");9 return true; // allow request to proceed10 }11
12 @Override13 public void postHandle(HttpServletRequest request,14 HttpServletResponse response,15 Object handler,16 ModelAndView modelAndView) {17 System.out.println("POST HANDLE");18 }19
20 @Override21 public void afterCompletion(HttpServletRequest request,22 HttpServletResponse response,23 Object handler,24 Exception ex) {25 System.out.println("AFTER COMPLETION");26 }27}AppConfig:
1@Configuration2public class AppConfig implements WebMvcConfigurer {3
4 @Autowired5 private MyCustomInterceptor myCustomInterceptor;6
7 @Override8 public void addInterceptors(InterceptorRegistry registry) {9 registry.addInterceptor(myCustomInterceptor)10 .addPathPatterns("/api/*")11 .excludePathPatterns("/api/update-user", "/api/delete-user");12 }13}PRE HANDLE CONTROLLER — getUser() executing POST HANDLE AFTER COMPLETION
4. Custom Annotations Foundation for Method-Level Interceptors
Why Custom Annotations?
For Type 2 interception (intercepting specific methods via AOP), we need a way to mark which methods should be intercepted. Custom annotations serve as these markers.
Additionally, annotations can carry metadata (values, keys, names) that the interceptor can read at runtime — essential for features like caching (what cache name?), logging (what log level?), etc.
How to Create a Custom Annotation
Use the @interface keyword:
1public @interface MyCustomAnnotation {2 // fields (declared as methods) go here3}This creates an annotation named MyCustomAnnotation. You can now use it like any built-in annotation:
1@MyCustomAnnotation2public void someMethod() { }5. Meta-Annotations `@Target` and `@Retention`
Meta-annotations are annotations applied on top of other annotations to configure their behavior. When creating a custom annotation, two meta-annotations are almost always required: @Target and @Retention.
`@Target` Where Can This Annotation Be Used?
@Target specifies the program elements on which the annotation is valid.
1@Target(ElementType.METHOD)2public @interface MyCustomAnnotation { }If you try to use @MyCustomAnnotation on a class or field after declaring @Target(ElementType.METHOD), the compiler will reject it.
◆ Common `ElementType` Values
| Value | Applies To |
|---|---|
ElementType.METHOD | Methods |
ElementType.TYPE | Classes, interfaces, enums |
ElementType.FIELD | Instance variables |
ElementType.CONSTRUCTOR | Constructors |
ElementType.PARAMETER | Method parameters |
ElementType.LOCAL_VARIABLE | Local variables |
ElementType.ANNOTATION_TYPE | Other annotations (meta-annotation use) |
Multiple targets:
1@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})2public @interface MyCustomAnnotation { }`@Retention` How Long Is the Annotation Kept?
@Retention controls when the annotation is available during the Java compilation/runtime pipeline.
◆ The Three Retention Policies
| Policy | In .java source | In .class bytecode | At JVM Runtime |
|---|---|---|---|
RetentionPolicy.SOURCE | ✅ Present | ❌ Discarded by compiler | ❌ Not available |
RetentionPolicy.CLASS | ✅ Present | ✅ Recorded | ❌ Ignored by JVM |
RetentionPolicy.RUNTIME | ✅ Present | ✅ Recorded | ✅ Available via Reflection |
◆ `RetentionPolicy.SOURCE`
1@Retention(RetentionPolicy.SOURCE)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation { }- The annotation exists in your
.javasource file. - The compiler discards it — it does NOT appear in the
.classfile. - Zero runtime impact.
- Real-world example:
@Override— exists only to help developers and the compiler catch override mistakes. Not needed at runtime.
◆ `RetentionPolicy.CLASS`
1@Retention(RetentionPolicy.CLASS)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation { }- The annotation IS written into the
.classbytecode file. - The JVM ignores it at runtime — you cannot read it via reflection.
- Useful for bytecode-level tools (e.g., static analyzers, bytecode weavers like AspectJ compile-time weaving).
◆ `RetentionPolicy.RUNTIME`
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation { }- Annotation is in
.classfile and available at runtime via Java Reflection. - This is what you need for AOP interceptors and Spring features.
- You can call
method.getAnnotation(MyCustomAnnotation.class)at runtime.
RetentionPolicy.RUNTIME.
Without it, the Spring AOP proxy cannot detect the annotation at runtime.Visual: Retention Policy Flow
6. Passing Data Through Annotations (Annotation Fields)
Overview
Annotations can carry data values — similar to fields in a class. These values can then be read by the interceptor to customize behavior (e.g., "which cache should I use?", "what log level?", "which key?").
Syntax Declaring Fields in an Annotation
Inside @interface, you declare fields as methods with no parameters and restricted return types:
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation {4 String name() default ""; // String field with default empty string5}◆ Rules for Annotation Fields
| Rule | Detail |
|---|---|
| No parameters | String name() ✅ — String name(int x) ❌ |
| No body | Just a declaration — no { } implementation |
| Restricted return types | Only: primitives (int, boolean, double, etc.), String, Class>, Enum, another Annotation, or arrays of these |
| Optional default | Use default to make the field optional when using the annotation |
Example Single Field
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation {4 String name() default "";5}Usage:
1@MyCustomAnnotation(name = "user")2public String getUser() {3 return "User data";4}Example Multiple Fields of Different Types
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation {4
5 int intKey() default 0;6
7 String stringKey() default "";8
9 Class<?> classTypeKey() default String.class;10
11 MyEnum enumKey() default MyEnum.DEFAULT;12
13 String[] stringArrayKey() default {};14}Usage:
1@MyCustomAnnotation(2 intKey = 10,3 stringKey = "userService",4 classTypeKey = User.class,5 enumKey = MyEnum.ACTIVE,6 stringArrayKey = {"read", "write"}7)8public String getUser() {9 return "User data";10}Reading Annotation Values via Reflection (Used by the Interceptor)
1Method method = ...; // obtained from JoinPoint2
3if (method.isAnnotationPresent(MyCustomAnnotation.class)) {4 MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);5 String name = annotation.name(); // reads "user"6 System.out.println("Annotation name value: " + name);7}This is exactly what the AOP interceptor does — at runtime, it reads the annotation's values to make decisions.
7. Type 2 AOP-Based Method Interceptor (After Controller, Around a Method)
Overview
This type of interception uses Spring AOP to intercept specific method calls — identified by a custom annotation on those methods. This goes deeper than the controller level; it can intercept any Spring-managed bean's method.
When to Use
- Intercept a service-layer method (not just controllers)
- Execute logic before/after methods annotated with a specific annotation
- Caching: intercept
@Cacheable-annotated methods - Logging: intercept
@Loggable-annotated methods - Authorization: intercept
@RequiresRole-annotated methods
Step 1 Create the Custom Annotation
1@Retention(RetentionPolicy.RUNTIME)2@Target(ElementType.METHOD)3public @interface MyCustomAnnotation {4 String name() default "";5}Step 2 Annotate the Target Method
1@Component2public class UserController {3
4 @GetMapping("/api/get-user")5 @MyCustomAnnotation(name = "user") // ← mark this method for interception6 public String getUser() {7 System.out.println("CONTROLLER — getUser() executing");8 return "User fetched";9 }10}Step 3 Create the AOP Interceptor
1@Component2@Aspect3public class MyCustomInterceptor {4
5 // Pointcut: intercept any method annotated with @MyCustomAnnotation6 @Around("@annotation(com.conceptencoding.learningspringboot.custominterceptor.MyCustomAnnotation)")7 public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable {8
9 // === BEFORE actual method ===10 System.out.println("DO SOMETHING BEFORE actual method");11
12 // Get the Method object from the join point13 MethodSignature signature = (MethodSignature) joinPoint.getSignature();14 Method method = signature.getMethod();15
16 // Check if the annotation is present (always true given our pointcut, but good practice)17 if (method.isAnnotationPresent(MyCustomAnnotation.class)) {18 MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);19 System.out.println("Annotation name value: " + annotation.name()); // prints "user"20 }21
22 // === Invoke the actual method ===23 Object result = joinPoint.proceed(); // calls getUser()24
25 // === AFTER actual method ===26 System.out.println("DO SOMETHING AFTER actual method");27
28 return result; // return the original method's return value29 }30}◆ Line-by-Line Explanation
| Line | Explanation |
|---|---|
@Aspect | Marks this class as an AOP aspect — Spring will scan it for pointcuts and advice |
@Component | Spring creates a bean of this class |
@Around(...) | This advice runs before AND after the matched method (@Around wraps both sides) |
"@annotation(...)" | Pointcut expression: match any method annotated with the fully-qualified annotation class |
ProceedingJoinPoint joinPoint | Represents the intercepted method call — gives access to metadata and control |
joinPoint.getSignature() | Returns the method signature (name, return type, parameters) |
method.isAnnotationPresent(...) | Checks at runtime (reflection) if the annotation is on this method |
method.getAnnotation(...) | Reads the annotation instance — gives access to field values like name() |
annotation.name() | Reads the name field value — "user" in this example |
joinPoint.proceed() | Calls the actual method. Without this call, the real method never executes |
Return result | Returns the original method's return value to the caller |
joinPoint.proceed() in an @Around advice. If you omit it, the actual controller/service method will never execute — the request silently returns null or the advice's return value.Step-by-Step Execution Flow
Console Output:
1DO SOMETHING BEFORE actual method2Annotation name value: user3CONTROLLER — getUser() executing4DO SOMETHING AFTER actual methodHow AOP Proxy Works (Internal)
When Spring starts up and sees @Aspect, it:
- Scans all beans for methods matching the pointcut expression.
- Wraps those beans in a proxy object (either JDK dynamic proxy or CGLIB).
- When a matched method is called, the proxy intercepts the call, runs the advice, and then (optionally) delegates to the real method.
Fully Qualified Annotation Path in Pointcut
The @annotation(...) pointcut requires the fully qualified class name of the annotation:
1@Around("@annotation(com.conceptencoding.learningspringboot.custominterceptor.MyCustomAnnotation)")This means:
- Package:
com.conceptencoding.learningspringboot.custominterceptor - Annotation class:
MyCustomAnnotation
@annotation not matching your methods at runtime, double-check the fully qualified name. A single typo will cause the interceptor to silently never fire.8. Comparison Handler Interceptor vs AOP Interceptor
| Feature | HandlerInterceptor | AOP (@Aspect) |
|---|---|---|
| Level | HTTP / Dispatcher Servlet level | Spring bean method level |
| Matching | URL path patterns | Annotation, method name, package, etc. |
| Scope | Only Spring MVC controllers | Any Spring-managed bean |
| Configuration | WebMvcConfigurer.addInterceptors() | @Aspect + @Component auto-detected |
| Access to HTTP | Yes (HttpServletRequest, HttpServletResponse) | No (only method metadata) |
| Typical use cases | Auth checks, request logging, rate limiting | Caching, method-level logging, custom behavior |
| Can block request? | Yes — preHandle() returns false | Yes — don't call joinPoint.proceed() |
9. Summary & Quick Reference
Handler Interceptor Checklist
- To do: Create class implementing
HandlerInterceptor - To do: Add
@Componentto the class - To do: Override
preHandle,postHandle,afterCompletionas needed - To do: In
AppConfig, implementWebMvcConfigurer - To do: Override
addInterceptors()and register with path patterns
AOP Method Interceptor Checklist
- To do: Create custom annotation with
@interface,@Retention(RUNTIME),@Target(METHOD) - To do: Add fields (optional) with restricted return types and
defaultvalues - To do: Add
@MyCustomAnnotationon the target method - To do: Create
@Aspect @Componentclass - To do: Write
@Around("@annotation(fully.qualified.AnnotationName)")method - To do: Use
joinPoint.proceed()to invoke the real method - To do: Read annotation values via reflection (
method.getAnnotation(...))
Key Bullets
- An interceptor is a mediator that runs before/after your actual code without changing it.
HandlerInterceptorhas 3 methods:preHandle(before controller),postHandle(after controller, success only),afterCompletion(always — likefinally).preHandlereturningfalseblocks the request.- Custom annotations use
@interfacekeyword. @Targetcontrols where the annotation can be used;@Retentioncontrols how long it lives.RetentionPolicy.RUNTIMEis required for Spring AOP to read annotations at runtime.- Annotation fields have restricted types: primitives,
String,Class>,Enum,Annotation, and arrays of these. - AOP interceptors use
@Aspect,@Component, and@Around("@annotation(...)"). joinPoint.proceed()invokes the actual method — never omit it in@Around.- Annotation values are read at runtime via Java Reflection:
method.getAnnotation(...).
10. Interview Notes
Q1: What is a Spring interceptor? Name the two types.
- A mediator that executes before or after your code. Types:
HandlerInterceptor(HTTP/controller level) and AOP-based interceptors (method level via@Aspect).
Q2: What are the three methods of HandlerInterceptor and when does each run?
preHandle()— before controller;postHandle()— after controller (success only);afterCompletion()— always, even on exception (likefinally).
Q3: What does returning false from preHandle() do?
- It stops the request chain. The controller never executes; no further interceptors run.
Q4: What is the difference between postHandle and afterCompletion?
postHandleruns only when no exception is thrown.afterCompletionalways runs, even when there's an exception — making it suitable for cleanup.
Q5: What keyword is used to create a custom annotation in Java?
@interface.
Q6: What are meta-annotations? Name the two most important ones.
- Annotations applied on top of another annotation. Most important:
@Target(where the annotation can be placed) and@Retention(how long the annotation is available).
Q7: Which RetentionPolicy must you use for Spring AOP interceptors and why?
RetentionPolicy.RUNTIME— because the AOP proxy reads the annotation at runtime via reflection.SOURCEorCLASSwould make the annotation invisible to the JVM at runtime.
Q8: What types are allowed as fields in a custom annotation?
- Primitives,
String,Class>,Enum, anotherAnnotation, or arrays of these. No arbitrary objects.
Q9: What is the AOP pointcut expression to intercept methods annotated with a custom annotation?
@annotation(fully.qualified.path.AnnotationName)
Q10: What happens if you forget joinPoint.proceed() in an @Around advice?
- The actual method is never called. The caller receives
null(or whatever the advice returns), and the real business logic is silently skipped.
Q11: What is the difference between HandlerInterceptor and AOP-based interception?
HandlerInterceptorworks at the HTTP/Dispatcher level (URL-pattern matching, access to request/response). AOP works at the Spring bean method level (annotation/pattern matching, no HTTP context).
11. Practice Questions
Easy
- What interface must you implement to create a
HandlerInterceptor? - In which Spring configuration method do you register a
HandlerInterceptor? - Which
RetentionPolicyvalue makes an annotation available at runtime? - What Java keyword creates a custom annotation?
- What does
joinPoint.proceed()do in an@Aroundadvice?
Medium
- Write a
HandlerInterceptorthat logs the URL of every incoming request and blocks any request containing the word "admin" in the URL. - Create a custom annotation
@RateLimit(maxRequests = 5)with a singleintfield. Describe how an AOP interceptor could use it to count method invocations. - What happens if
preHandle()throws an exception — doesafterCompletion()still run? - Explain why
@Retention(RetentionPolicy.SOURCE)would cause an AOP interceptor to silently never fire. - How does Spring create the AOP proxy — what are the two proxy strategies used?
Hard
- Design a complete
@Loggableannotation-based AOP interceptor that: logs the method name, logs input parameters, logs return value, and logs execution time in milliseconds. Write the full annotation class and the full@Aspectclass. - Can a
HandlerInterceptorand an AOP interceptor both apply to the same controller method? Describe the exact execution order. - If you have two
HandlerInterceptors registered inaddInterceptors(), in what order dopreHandleandafterCompletionexecute? (Hint: they are not the same order.) - What would you use for authentication at the HTTP layer vs. authorization at the method level —
HandlerInterceptoror AOP? Justify your answer. - Explain how
@Transactionalin Spring uses the same AOP interception mechanism described in this guide. What is the pointcut? What is the advice? What doesjoinPoint.proceed()correspond to in the transaction flow?
@Cacheable), logging, and authentication/authorization topics covered in later parts of this series.Mastery check
How well can you recall this?
Finished this lesson?