You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JWT认证时Autowired注入的StudentService出现空指针异常

JWT权限控制使用@PreAuthorize时出现StudentService空指针异常,antMatcher配置时正常

问题描述

为多角色实现JWT认证功能时遇到异常:通过WebSecurity配置类的antMatcher配置接口URL时,API可正常运行;但使用@PreAuthorize注解做权限控制时,抛出空指针异常,提示StudentService实例为null。

控制器代码

package com.shashank.controller;
.........
@RestController
@CrossOrigin
public class StudentController {
    @Autowired
    StudentService studentService;

    @GetMapping("/api/student/stu")
    @PreAuthorize("hasRole('User')")
    private List<Student> getAllUStudent(){
        System.out.println("Get Call");
        return studentService.getAllStudent();
    }
}

控制台错误信息

java.lang.NullPointerException: Cannot invoke "com.shashank.service.StudentService.getAllStudent()" because "this.studentService" is null
    at com.shashank.controller.StudentController.getAllUStudent(StudentController.java:28) ~[classes/:na]

解决方案

问题根源在于控制器方法的访问修饰符:你将getAllUStudent()定义为private,而Spring AOP(@PreAuthorize的实现依赖AOP)无法代理私有方法,导致Spring无法正确注入StudentService,同时权限控制逻辑也无法生效。

修复步骤

  1. 将方法的访问修饰符从private改为public
  2. 确保Spring配置类已开启方法级安全,添加注解:@EnableGlobalMethodSecurity(prePostEnabled = true)

修改后的方法示例:

@GetMapping("/api/student/stu")
@PreAuthorize("hasRole('User')")
public List<Student> getAllUStudent(){
    System.out.println("Get Call");
    return studentService.getAllStudent();
}

内容的提问来源于stack exchange,提问作者Shashank Trivedi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:11:35