此问题已在此处有答案:
What is a NullPointerException, and how do I fix it?(12个回答)
上个月关门了。
我正在做一个Sping Boot 项目,在那里我实现了Spring Security来管理JWT身份验证。我有一个ProductController,其中自动连接了一个ProductService。当我将**@PreAuthorizeannotation添加到我的一个控制器方法时,我遇到了与productService字段相关的NullPointerException**。
注意:我在添加Spring Security后遇到了这个问题
下面是我的控制器代码:
@RestController
@RequestMapping("/product")
@RequiredArgsConstructor
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping
@PreAuthorize("hasAuthority('CLIENT')")
private Page<ProductDTO> getProducts(
@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "10") int size) {
Pageable pageable = PageRequest.of(page, size);
return productService.findAll(pageable);
}
// ...
}
我收到的错误消息是:
java.lang.NullPointerException: Cannot invoke "com.arinashoe.catalogservice.service.ProductService.findAll(org.springframework.data.domain.Pageable)" because "this.productService" is null
但是,当我删除@PreAuthorize注解时,该方法可以正常工作。
我正在使用Sping Boot 3.1.2,我遵循本教程实现JWT身份验证:[https://www.bezkoder.com/spring-boot-jwt-authentication/].
是什么原因导致了这个问题,我该如何解决?
我也尝试了下面的方法与@PreAuthorize,它的工作正常:
@GetMapping("/test")
@PreAuthorize("hasAuthority('CLIENT')")
private String testMethod(Authentication authentication) {
if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
String userId = userDetails.getUsername(); // Assuming username represents the userId
return "User ID: " + userId;
}
return "User ID not available";
}
任何关于如何解决这个问题的见解或建议将不胜感激。
1条答案
按热度按时间ycggw6v21#
您可以查看@Service是否已定义