spring boot 拦截器 WebMvcConfigurer 无效

今天配置WebMvcConfigurer拦截器,无论怎么配置,都没有生效。代码如下:

@Configuration
@EnableConfigurationProperties(JwtConfig.class)
public class WebAppConfigurer implements WebMvcConfigurer {

    @Autowired
    private JwtConfig props;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //配置登录拦截器
        registry.addInterceptor(new UserInterceptor(props)).addPathPatterns("/**");
    }
}
public class UserInterceptor implements HandlerInterceptor {

    private JwtConfig props;

    //定义一个线程域,存放登录的对象
    private static final ThreadLocal<Account> user = new ThreadLocal<>();

    public UserInterceptor() {
        super();
    }

    public UserInterceptor(JwtConfig props) {
        this.props = props;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查询Token
        String token = CookieUtils.getCookieValue(request, props.getCookieName());
        if (StringUtils.isBlank(token)) {
            //用户未登录,返回401,拦截
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //用户已登录,获取用户信息
        try {
            Account userInfo = JwtUtils.getUserInfo(props.getPublicKey(), token);
            //放入线程域中
            user.set(userInfo);
            return true;
        } catch (Exception e) {
            //抛出异常,未登录
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //过滤器完成后,从线程域中删除用户信息
        user.remove();
    }

    /**
     * 获取登陆用户
     * @return
     */
    public static Account getLoginUser() {
        return user.get();
    }
}

通过debug测试加载顺序,发现

WebAppConfigurer的addInterceptors方法一直没有加载到,看了下自己的springboot启动类,其中配置有scanBasePackages,可能因为这个配置所有component没有扫描上,最后又加上了拦截器配置所在的包@ComponentScan(basePackages={"com.zc.test.item.*"}),启动正常!
@SpringBootApplication(scanBasePackages = "com.zc.test.*")
@ComponentScan(basePackages={"com.zc.test.item.*"})
public class ItemApplication {

    public static void main(String[] args) {
        SpringApplication.run(ItemApplication.class, args);
    }

}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值