我使用以下代码注册了我的拦截器
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
...
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor( myInterceptor() );
}
...
}
这里是拦截器定义
public class MyInterceptorimplements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Check to see if the handling controller is annotated
for (Annotation annotation : Arrays.asList(handler.getClass().getDeclaredAnnotations())){
if (annotation instanceof MyAnnotation){
... do something
但是handler.getClass()。getDeclaredAnnotations()没有返回截获的Controller的类级别注释。
我只能得到方法级注释,这不是我想要的。
相同的拦截器可以正常使用xml配置(使用Spring 3):
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="myInterceptor"/>
</list>
</property>
</bean>
有没有办法在Spring 4中提供类级信息?
根据 In a Spring-mvc interceptor, how can I access to the handler controller method? &#34; HandlerInterceptors只允许您访问HandlerMethod&#34;使用上面的配置。但是获取类级别信息的替代配置是什么?
答案 0 :(得分:7)
您可以使用处理程序方法在拦截器中访问spring控制器类级别注释。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle");
HandlerMethod hm = (HandlerMethod)handler;
Method method = hm.getMethod();
if(method.getDeclaringClass().isAnnotationPresent(Controller.class)) {
if(method.isAnnotationPresent(ApplicationAudit.class)) {
System.out.println(method.getAnnotation(ApplicationAudit.class).value());
request.setAttribute("STARTTIME",System.currentTimemillis());
}
}
return true;
}