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");
        }
    }
    
  • 相关阅读:
    Property总结
    静态类和 关于什么时候使用“静态方法”
    最简单的MVVM结构(学习)
    依赖属性和附加属性1(转载)
    Nested & Access modifiers
    Template methord
    WPF 绑定及惯用法(一) 转载自loveis715
    关于Property赋值
    Different Binding RelativeSource Mode
    依赖属性和附加属性2(转载)
  • 原文地址:https://www.cnblogs.com/zhenhunfan2/p/13529622.html
Copyright © 2011-2022 走看看