SpringBoot中添加拦截器,在拦截器中注入其他类的时候出现空指针异常解决办法

简介: SpringBoot中添加拦截器,在拦截器中注入其他类的时候出现空指针异常解决办法

拦截器代码

/**
 *
 * 记录用户轨迹
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    SysLogDao sysLogDao

    /**
     * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
     */

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了AdminInterceptor的afterCompletion方法");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
        LocalDateTime now = LocalDateTime.now();
        Object user = request.getSession().getAttribute("userName");
        Object msg = request.getSession().getAttribute("msg");
        if (user != null && msg != null) {
            SysLog sysLog = new SysLog();
            sysLog.setLogId(IDUtils.getId());
            sysLog.setUserName(user.toString());
            sysLog.setMsg(msg.toString());
            sysLog.setCreateTime(dateTimeFormatter.format(now));
            SysLog save = sysLogDao.save(sysLog);
        }

    }
}

注入拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //静态资源:*.css  *.js
        //Spring Boot 已经做好了静态资源映射
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(new AdminInterceptor());
        interceptorRegistration.addPathPatterns("/**").excludePathPatterns("/","/login");
    }
}

调用接口时发现,SysLogDao 并没有被注入进来!明明代码写的没问题,为什么不能正常注入SysLogDao 呢?

仔细观察我们自定义的配置类WebConfig ,在添加拦截器的时候用的是new AdminInterceptor(),如果想要拦截器生效,必须将拦截器配置到WebMvc的配置类中,就是我们自定义的WebConfig 类。现在添加拦截器的时候是 new 了一个拦截器,也就是说并没有将拦截器托管给IOC容器,拦截器加载是在springcontext创建之前完成的,所以就无法引入Spring的bean对象。

解决办法:让Bean对象提前加载,将拦截器注入进来。
方式一:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    public AdminInterceptor adminInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //静态资源:*.css  *.js
        //Spring Boot 已经做好了静态资源映射
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(adminInterceptor);
        interceptorRegistration.addPathPatterns("/**").excludePathPatterns("/","/login");
    }
}

方式二:
拦截器无需增加@Component注解,在WebConfiguration类中使用@Bean注解将拦截器注成bean。

/**
 *
 * 登录检查
 * 记录用户轨迹
 */
public class AdminInterceptor implements HandlerInterceptor {
...
}
@Configuration
public class WebConfig implements WebMvcConfigurer {

     @Bean
    public AdminInterceptor adminInterceptor(){
        return new AdminInterceptor();
   }
  
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //静态资源:*.css  *.js
        //Spring Boot 已经做好了静态资源映射
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(adminInterceptor());
        interceptorRegistration.addPathPatterns("/**").excludePathPatterns("/","/login");
    }
}
目录
相关文章
|
2月前
|
Java
springboot字段注入@value细节
springboot字段注入@value细节
25 1
|
2月前
|
Java
springboot自动注入避坑
springboot自动注入避坑
24 1
|
2天前
|
资源调度 监控 关系型数据库
实时计算 Flink版操作报错合集之处理大量Join时报错空指针异常,是什么原因
在使用实时计算Flink版过程中,可能会遇到各种错误,了解这些错误的原因及解决方法对于高效排错至关重要。针对具体问题,查看Flink的日志是关键,它们通常会提供更详细的错误信息和堆栈跟踪,有助于定位问题。此外,Flink社区文档和官方论坛也是寻求帮助的好去处。以下是一些常见的操作报错及其可能的原因与解决策略。
实时计算 Flink版操作报错合集之处理大量Join时报错空指针异常,是什么原因
|
5天前
|
编译器 C++
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
virtual类的使用方法问题之在C++中获取对象的vptr(虚拟表指针)如何解决
|
27天前
|
运维
系统日志使用问题之如何防止在打印参数时遇到NPE(空指针异常)
系统日志使用问题之如何防止在打印参数时遇到NPE(空指针异常)
java.lang.NullPointerExceptionMybatisPlus出现,测试,java.lang.NullPointe,空指针异常,public方法少写了一个字段,没加注解
java.lang.NullPointerExceptionMybatisPlus出现,测试,java.lang.NullPointe,空指针异常,public方法少写了一个字段,没加注解
|
2月前
|
Java
springboot自定义拦截器,校验token
springboot自定义拦截器,校验token
109 6
|
2月前
|
Java
2022蓝桥杯大赛软件类国赛Java大学B组 左移右移 空间换时间+双指针
2022蓝桥杯大赛软件类国赛Java大学B组 左移右移 空间换时间+双指针
27 3
|
2月前
|
存储 Java C#
C++语言模板类对原生指针的封装与模拟
C++|智能指针的智能性和指针性:模板类对原生指针的封装与模拟
|
2月前
|
C++
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)
28 0
C++职工管理系统(类继承、文件、指针操作、中文乱码解决)