zoukankan      html  css  js  c++  java
  • 拦截器中不能注入Java bean?

    一、如何实现拦截器

    在Spring Boot项目中,拦截器经常被用来做登陆验证,日志记录等操作。拦截器是Spring提供的,所以可以将拦截器注成bean,由IOC容器来管理。实现拦截器的方式很简单,主要由以下两个步骤:

    1. 自定义拦截器类实现HandlerInterceptor接口

    2. 自定义WebMvc配置类实现WebMvcConfigurer接口,添加自定义拦截器类

    简要实现代码如下:

    自定义拦截器 LoginInterceptor

    public class LoginInterceptor implements HandlerInterceptor {
     
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     
            String token = request.getHeader("token");
            if(StringUtils.isEmpty(token)){
           ...
                return false;
            }
            return true;
        }
    }
    

    配置自定义拦截器:

    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
     
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginInterceptor())
                 // 拦截的请求
                    .addPathPatterns("/**")
                 // 不用拦截的请求
                    .excludePathPatterns("/login");
        }
    }
    

    这个拦截器的主要作用就是拦截所有访问请求,验证所带token是否有效,当token验证成功后,才能访问我们的业务接口。这时候就需要提供一个验证token有效性的接口,在拦截器中验证token,由于拦截器是Spring提供的,因此很容易想到使用@Component注解将拦截器注成一个 bean。然后使用@Autowired注解将验证token的类注入到拦截器进行验证。

    改造完的代码如下:

    验证token接口类:

    @Component
    public class TokenUtil {
        /**
         * 验证token 是否有效
         */
        public boolean checkToken(String token){
            ...
        }
    }
    

    改造完的拦截器代码如下:

    @Component
    public class LoginInterceptor implements HandlerInterceptor {
     
        @Autowired
        private TokenUtil tokenUtil;
     
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if(!tokenUtil.checkToken(token)){
                ...
                return false;
            }
            return true;
        }
    }
    

    调用接口时发现,TokenUtil并没有被注入进来!明明代码写的没问题,为什么不能正常注入TokenUtil呢?

    仔细观察我们自定义的配置类WebConfiguration,在添加拦截器的时候用的是new LoginInterceptor()如果想要拦截器生效,必须将拦截器配置到WebMvc的配置类中,就是我们自定义的WebConfiguration类。现在添加拦截器的时候是 new 了一个拦截器,也就是说并没有将拦截器托管给IOC容器,所以就无法引入Spring的bean对象

    二、如何将拦截器托管给IOC容器

    解决问题的思路也很简单,就是将拦截器也托管给IOC容器,这样容器内的对象就可以相互注入了。总共有以下三种方式进行处理上述问题。

    2.1 在WebConfiguration注入拦截器

    拦截器代码不变,在拦截器上使用@Component,同时在WebConfiguration中使用@Autowired注解将拦截器注入。

    拦截器代码:

    @Component
    public class LoginInterceptor implements HandlerInterceptor {
    } 

    配置类代码: 

     
    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
     
        @Autowired
        private LoginInterceptor loginInterceptor;
     
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(loginInterceptor);
        }
    }
    

    2.2 在WebConfiguration将拦截器注成bean

    拦截器无需增加@Component注解,在WebConfiguration类中使用@Bean注解将拦截器注成bean。

    拦截器代码:

    public class LoginInterceptor implements HandlerInterceptor {
    }
    

    配置类代码:

     
    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
     
        @Bean
        public LoginInterceptor loginInterceptor(){
            return new LoginInterceptor();
        }
     
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor( loginInterceptor());
        }
    }
    

    2.3 通过构造器处理

    思路是在WebConfiguration类中注入需要的验证token的业务类,然后在初始化拦截器的时候将业务类通过构造器带入拦截器中,这样就不用把拦截器注成Spring Bean对象了。

    拦截器代码:

     
    public class LoginInterceptor implements HandlerInterceptor {
     
        private TokenUtil tokenUtil;
     
        public LoginInterceptor(TokenUtil tokenUtil) {
            this.tokenUtil = tokenUtil;
        }
    } 

    配置类代码:

    @Configuration
    public class WebConfiguration implements WebMvcConfigurer {
     
        @Autowired
        private TokenUtil tokenUtil;
     
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginInterceptor(tokenUtil));
        }
    }
    

    三、总结

    网上关于拦截器的代码基本都是通过new一个拦截器进行配置的,这时候就会出现无法注入其他bean的情况。很多人想当然地直接在拦截器加@Component注解使其成为一个bean对象。这是一种错误的做法。我们需要保证的是在WebMvc配置类中添加的拦截器是Spring 的一个bean对象,也就是说我们需要将拦截器注成一个bean,同时将这个bean添加的WebMvc配置类中。

    我话讲完!谁赞成?谁反对?
  • 相关阅读:
    POJ 1330 Nearest Common Ancestors(LCA Tarjan算法)
    LCA 最近公共祖先 (模板)
    线段树,最大值查询位置
    带权并查集
    转负二进制
    UVA 11437 Triangle Fun
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
  • 原文地址:https://www.cnblogs.com/wffzk/p/15524407.html
Copyright © 2011-2022 走看看