• 如何在Interceptor中使用@Autowired


    config类:

    @Configuration
    public class WebAdminInterceptorConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new WebAdminInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/static");
        }
    }
    

    Interceptor类:

    public class WebAdminInterceptor implements HandlerInterceptor {
    
        @Autowired
        private RedisService redisService;
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            redisService.get("aaa"); //redisService为null
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    
        }
    }
    

    问题描述:

    在Interceptor中,自动注入的对象为null

    解决方案:

    修改Config类如下:

    @Configuration
    public class WebAdminInterceptorConfig implements WebMvcConfigurer {
    
        @Bean
        WebAdminInterceptor webAdminInterceptor(){
            return new WebAdminInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(webAdminInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/static");
        }
    }
    
  • 相关阅读:
    request转换为java bean
    idea中快捷键
    idea中Terminal显示中文乱码
    idea解决tomcat控制台中文乱码问题
    需要看的url
    常用网站
    反射
    5、运算符
    4、变量
    2、Hello Word讲解
  • 原文地址:https://www.cnblogs.com/zhenhunfan2/p/13529622.html
Copyright © 2020-2023  润新知