springmvc 拦截器中 @Autowired注入

1.定义拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //redisUtil  do something...
        if() {
        	return true;
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"status\":500,\"error\":\"Internal Server Error\",\"message\":\"Token失效,请重新登录\"}");
        response.flushBuffer();
        return false;
    }
}
2.添加拦截器
@Configuration
//此方式是完全托管,自动配置失效 可以实现 WebMvcConfigurer
public class Configurer extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
       //此时拦截器是无法正常持续Autowired类方法的,注入为空(拦截器加载的时间点在springcontext之前)
        registry.addInterceptor(loginInterceptor());
    }
3 //定义Bean
    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }
}

你可能感兴趣的:(springmvc)