从存储库中的Spring Security获取当前userId的任何方法?

问题描述

我有一个带有多个本机查询的Spring Data存储库,所有这些查询都需要由当前登录用户过滤(例如,“ and where user_id =?”应该包含在每个查询中)。有没有一种方法可以从存储库中通过Spring Security访问userId并在查询中使用它?我可以在控制器中获取userId并将其作为方法参数传递给仓库,但是当涉及多个方法时,这将变得非常重复。 来自以下仓库的示例查询

@Query(value = "SELECT COUNT(disTINCT project_id) FROM reports r WHERE r.month = ?1 AND r.year = ?2",nativeQuery = true)
    int getTotalProjectsByMonth(int month,int year);

解决方法

您可以尝试

SecurityContextHolder.getContext().getAuthentication();