Applying an interceptor globally means registering it so it runs for every incoming request across the entire application, rather than being tied to a single controller. In Spring MVC this is done through a central configuration class rather than an annotation on the interceptor itself.
Key Points: • Implement WebMvcConfigurer in a @Configuration class to hook into Spring MVC's configuration callbacks. • Override addInterceptors(InterceptorRegistry registry) and call registry.addInterceptor(new MyInterceptor()) to register it. • By default, an added interceptor applies to all paths ("/**"); addPathPatterns and excludePathPatterns can narrow or exclude specific routes. • Multiple interceptors can be registered with an explicit order, controlling which one runs first when several apply to the same request. • If the interceptor itself needs injected dependencies, define it as a @Component or a @Bean so Spring can wire it before registering it in the registry.
Example: A logging interceptor registered with no path pattern restrictions runs on every request in the application, while an authentication interceptor might be scoped with addPathPatterns("/admin/**") to apply only to admin routes.
Code Example:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoggingInterceptor());
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/admin/**");
}
}Interview Tip: A concise interview answer is:
"I register global interceptors in a @Configuration class that implements WebMvcConfigurer, overriding addInterceptors to call registry.addInterceptor. Leaving out addPathPatterns applies the interceptor to every request, while specifying it scopes the interceptor to just the routes that need it."