Spring Boot 2.0拦截请求的HandlerMethod

时间:2018-11-24 17:33:58

标签: java spring spring-boot

我正在从Spring Boot 1.x升级到Spring Boot 2.0的过程中,并且发现我已经开始在HandlerInterceptor上出现类强制转换错误。

例如,在一个HandlerInterceptor中,我查看控制器方法/端点是否用@AdminOnly注释以限制对某些端点的访问。

@Component
public class AdminOnlyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object handler) {
        HandlerMethod hm = (HandlerMethod) handler;
        Method method = hm.getMethod();
        if (method.getDeclaringClass().isAnnotationPresent(RestController.class) && (method.isAnnotationPresent(AdminOnly.class) || method.getDeclaringClass().isAnnotationPresent(AdminOnly.class))) {
            // Some Logic returning true or false
        }
        return true;
    }
}

这在Spring Boot 1.5.x中有效。

升级后,我现在得到以下异常:

java.lang.ClassCastException: org.springframework.web.servlet.resource.ResourceHttpRequestHandler cannot be cast to org.springframework.web.method.HandlerMethod

我在migration guide中找不到任何相关内容。我该如何升级,但要保持拦截器正常工作?

1 个答案:

答案 0 :(得分:0)

看来Spring Boot 2.x拦截器现在也可以处理静态资源请求,因此在注册拦截器时需要手动排除这些请求,如下所示:

@Configuration
public class ControllerConfiguration implements WebMvcConfigurer {

    private final AdminOnlyInterceptor adminInterceptor;

    @Autowired
    public ControllerConfiguration(AdminInterceptor adminInterceptor) {
        this.adminInterceptor = adminInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminInterceptor)
                .addPathPatterns("/rest-api-root/**"); // White list paths
                //.excludePathPatterns("/static-resource-root/**"); // Black list paths
    }
}