Is it possible to wire a Spring MVC Interceptor using annotations and if so could someone provide me with an example of how to do so?
By wire via annotation I am referring to doing as little in the XML configuration as possible. For example in this configuration file I found at http://www.vaannila.com/spring/spring-interceptors.html;
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" p:interceptors-ref="loggerInterceptor" /> <bean id="loggerInterceptor" class="com.vaannila.interceptor.LoggerInterceptor" />
How little configuration could you get away with there? I imagine an @Autowired
would remove the need to explicitly declare the bean in line 2, but would it be possible to get rid of line 1 with an annotation as well?
Spring Handler Interceptor The HandlerInterceptor contains three main methods: prehandle() – called before the execution of the actual handler. postHandle() – called after the handler is executed. afterCompletion() – called after the complete request is finished and the view is generated.
To work with interceptor, you need to create @Component class that supports it and it should implement the HandlerInterceptor interface. preHandle() method − This is used to perform operations before sending the request to the controller. This method should return true to return the response to the client.
Spring Interceptor are used to intercept client requests and process them.
Stumbled upon this question while searching exactly this. Finally I found out that it works in Spring 3.1 using @EnableWebMVC in conjunction with WebMvcConfigurerAdapter.
Simple Example:
@Configuration @EnableWebMvc @ComponentScan(basePackages="webapp.base.package") public class WebApplicationConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoggerInterceptor()); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With