Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to wire a Spring MVC Interceptor using annotations?

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?

like image 273
James McMahon Avatar asked Dec 08 '10 15:12

James McMahon


People also ask

How does interceptor work in Spring MVC?

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.

How do you call an interceptor from a spring boot?

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.

Which interceptor is used in an application when maintenance page needs to be shown?

Spring Interceptor are used to intercept client requests and process them.


1 Answers

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());     }  } 
like image 174
Markus Kreusch Avatar answered Sep 24 '22 10:09

Markus Kreusch