zoukankan      html  css  js  c++  java
  • 如何在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");
        }
    }
    
  • 相关阅读:
    RabbitMQ详解(一)——安装
    智能风控平台核心之风控决策引擎(一)
    Redis6详解(一)——概述与安装
    SpringMVC(一)——入门案例
    数据结构与算法(一)——概述
    JDK1.8源码(二)——java.lang.Integer类
    设计模式(一)——概述
    Java基础(五)——String
    first 博客园
    Django
  • 原文地址:https://www.cnblogs.com/zhenhunfan2/p/13529622.html
Copyright © 2011-2022 走看看