1、问题概述?

1、拦截器的主要作用包括权限验证、日志记录、性能监控等通用行为处理。

2、我们经常需要拦截中调用其他service,实现对数据库的相关操作

那么在springboot的Interceptor中如何注入对应的service呢?

2、Interceptor中注入service的方式?

2.1、springboot中自定义拦截器

1、在拦截器中直接使用如下代码无法直接注入:

@Autowired  private SystemLogService systemLogService;

2、需要创建构造器,通过构造传参的方式注入引用。

@Component
public class SystemOperationLogInterceptor implements HandlerInterceptor {

    private TestService testService;

    public SystemOperationLogInterceptor(TestService testService){
        this.testService=testService;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        testService.addSystemLog();
        return true;
    }
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2.2、在WebMvcConfigurer中注册拦截器

1、InterceptorConfiguration 通过注解@Configuration修饰,启动的时候加载。

2、通过如下代码向拦截器注入service 

@Autowired
private TestService testService;

registry.addInterceptor(new SystemOperationLogInterceptor(testService))
                .addPathPatterns(addPathPatterns)
                .excludePathPatterns(excludePathPatterns);

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

    @Autowired
    private TestService testService;

    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("=============初始化拦截器===============");
        String[] addPathPatterns = {//拦截所有请求
                "/**"
        };
        String[] excludePathPatterns = {//设置不想拦截的路径
                "/*/*.js","/*.js"
        };
        registry.addInterceptor(new SystemOperationLogInterceptor(testService))
                .addPathPatterns(addPathPatterns)
                .excludePathPatterns(excludePathPatterns);
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐