SpringBoot拦截器注入 Service 为空问题

SpringBoot拦截器注入 Service 为空问题

问题:

在一个项目中,想在通过接口CRUD后,通过拦截器postHandle方法调用service层记录下CRUD的操作。

然而却报错:service为空 注入失败。

public class OperationRecordInterceptor implements HandlerInterceptor {

    @Autowired
    private OperationRecordServiceImpl operationRecordService ;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        
        //在此处报错 operationRecordService为空
		operationRecordService.xxx();
    }


}

解决方案

将该拦截器添加到容器中,在注册拦截器时用容器中的拦截器,而不是new一个拦截器

1.拦截器类上加@Compent

@Component
public class OperationRecordInterceptor implements HandlerInterceptor 

2.注册拦截器用容器中的拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

	//自动配置拦截器
    @Autowired
    OperationRecordInterceptor operationRecordInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

				//使用容器中的,而不是new一个
        registry.addInterceptor(operationRecordInterceptor)
                .addPathPatterns("/student/addStudent",
                        "/student/deleteById","/student/update");
    }
}
原文地址:https://www.cnblogs.com/iamwatershui/p/14255112.html