使用JWT认证时Autowired注入的StudentService出现空指针异常
问题描述
为多角色实现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,同时权限控制逻辑也无法生效。
修复步骤
- 将方法的访问修饰符从
private改为public - 确保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
相关产品推荐
相关产品推荐

