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);
}
}
2269

被折叠的 条评论
为什么被折叠?



