【发布时间】:2015-03-31 10:36:58
【问题描述】:
我使用以下代码注册了我的拦截器
@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() 没有返回被截获的控制器的类级别注释。
在这种情况下,我只能获得方法级别的注释,这不是我想要的。
同样的拦截器适用于 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? 使用上面的配置,“HandlerInterceptors 只会让你访问 HandlerMethod”。但是获取类级别信息的替代配置是什么?
【问题讨论】:
-
你在比较苹果和橘子。
DefaultAnnotationHandlerMapping是旧版本并且已弃用的较新版本(包括 java 配置)使用RequestMethodHandlerMapping在 XML 中使用它会导致相同的结果(如果您想将苹果与苹果进行比较)。如前所述,您将获得HandlerMethod类型的对象,使用该类的getBean方法来获取执行您请求的实际对象。或者使用getMethod获取选中的方法。 -
@selvinsource 你确定
handler对象是你认为的类型吗?它可能是一个代理对象,因此getDeclaredAnnotations可能无法处理它。 -
感谢您的输入,我找到了解决方案:((HandlerMethod)handler).getBean().getClass().getDeclaredAnnotations())
标签: java spring spring-mvc