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");
        }
    }
    
  • 相关阅读:
    设计模式 设计原则 何为设计
    面向对象 多态
    两个简易的对拍程序
    各类有用的神奇网站
    乘法逆元
    树链剖分
    Markdown的用法
    vimrc 的配置
    luogu【P1144】最短路计数
    【娱乐】收录各种神奇知乎问答
  • 原文地址:https://www.cnblogs.com/iamwatershui/p/14255112.html
Copyright © 2011-2022 走看看