@ServletComponentScan 注解加上后拦截器失效

今天项目中遇到一个问题, 当使用@ServletComponentScan注解标注时, 原来正常的自定义MyInterceptor突然失效了,项目代码如下;
MyInterceptor 代码如下

public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("check MyInterceptor................");
        HandlerMethod method = (HandlerMethod) handler;
        if (method == null) return true;
        if (method.getMethod().isAnnotationPresent(xxx.class)) {
            return true;
        }else{
            System.out.println("check UserLogin");
        }
        return false;
    }
...
...
}

Configuration配置文档如下

@Configuration
public class ZcWebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}

@ServletComponentScan 配置如下

@SpringBootApplication
@ServletComponentScan
public class ApiApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiApplication.class, args);
    }
}

具体原因暂时不知道,
结论是引入@ServletComponentScan时会扫描标注@WebFilter的自定义filter, 并且加载到项目中,
但是springboot项目中自定义的拦截器会被屏蔽. 所以只能改用使用@Configuration,配置注册为Bean的方式实现自定义filter

自定义filter使用详见本人另一个博客
https://blog.csdn.net/yangsnow_rain_wind/article/details/81326782

阅读更多
换一批

没有更多推荐了,返回首页