zoukankan      html  css  js  c++  java
  • 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");
        }
    }
    
  • 相关阅读:
    Python学习笔记之操作yalm
    Python学习笔记之多线程
    Python学习笔记之网络编程
    Python学习笔记之面对象与错误处理
    Python学习笔记之装饰器
    Python学习笔记之内置模块
    Python学习笔记之函数与正则
    PAT甲级1049. Counting Ones
    PAT甲级1045. Favorite Color Stripe
    PAT甲级1034. Head of a Gang
  • 原文地址:https://www.cnblogs.com/iamwatershui/p/14255112.html
Copyright © 2011-2022 走看看