An interceptor in Spring Boot is a component that intercepts incoming requests and outgoing responses in order to add custom functionality. This is particularly useful when you want to add functionality to multiple requests or responses in a centralized manner.
Here’s an example of using an interceptor to add a “car” header to all responses:
- Create a class for the interceptor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; @Component public class CarInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { response.addHeader("car", "Tesla Model S"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } |
- Register the interceptor in the Spring Boot application configuration:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Autowired CarInterceptor carInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(carInterceptor).addPathPatterns("/**"); } } |
Now, every time a request is made to your Spring Boot application, the CarInterceptor
will be executed and the response will contain a “car” header with the value “Tesla Model S”.
Here is an example of a Spring Boot application class:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
typescriptCopy code<code>package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } |
The @SpringBootApplication
annotation is a convenience annotation that is equivalent to declaring @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
. It enables the automatic configuration of Spring Boot and enables the scanning of components in the specified package and its sub-packages.