拦截器中无法注入service

在拦截器中注入service时,报空指针.发现拦截器的加载时间在Spring上下文之前加载,所以需要提前将拦截器注册到Spring上下文中

失败案例:

package com.example.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @Author: sun

  • @Email:

  • @Date:

  • @Time: 10:41

  • @Description: 此乃拦截器之注册
    */
    @Configuration
    public class UserInterceptorRegister extends WebMvcConfigurerAdapter {

    /**

    • 注册拦截器
    • @param registry
      /
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
      /
      *
      • 多个拦截器组成一个拦截器链
      • addPathPatterns 用于添加拦截规则
      • excludePathPatterns 用户排除拦截
      • 拦截路径配置:例:拦截所有:"/"
        */
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/userinfo/
        ");
        //registry.addInterceptor(new InterceptorName2()).addPathPatterns("/");
        //registry.addInterceptor(new InterceptorName3()).addPathPatterns("/
        ");以此类推
        super.addInterceptors(registry);
        }
        }

成功案例:

package com.example.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @Author: sun
  • @Email: szw3366@126.com
  • @Date: 2017/12/4
  • @Time: 10:41
  • @Description: 此乃拦截器之注册
    /
    @Configuration
    public class UserInterceptorRegister extends WebMvcConfigurerAdapter {
    /
    *
    *
    • @return
      /
      @Bean
      public HandlerInterceptor getUserInterceptor(){
      return new UserInterceptor();
      }
      /
      *
    • 注册拦截器
    • @param registry
      /
      @Override
      public void addInterceptors(InterceptorRegistry registry) {
      /
      *
      • 多个拦截器组成一个拦截器链
      • addPathPatterns 用于添加拦截规则
      • excludePathPatterns 用户排除拦截
      • 拦截路径配置:例:拦截所有:"/"
        */
        registry.addInterceptor(getUserInterceptor()).addPathPatterns("/userinfo/
        ");
        //registry.addInterceptor(new InterceptorName2()).addPathPatterns("/");
        //registry.addInterceptor(new InterceptorName3()).addPathPatterns("/
        ");以此类推
        super.addInterceptors(registry);
        }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值