Spring 通过注释为当前用户传递参数值

Spring passing parameter values via annotations for current user

我正在开发一些社交系统,我想做一些自动将 loggedUser 注入方法参数的注释。

我试过使用 AOP 但官方文档说:

Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. Methods can have default values.

public void getLoggedUserDetails( @CurrentUser User user){
//some logic
}

是否可以使用 Aspects 和注释来做到这一点,或者我应该寻找其他解决方案?

有一个 @AuthenticationPrincipal,它适用于控制器方法参数。见 here

@Controller
class UserController {


    @GetMapping("/self")
    public ResponseEntity<User> demo(@AuthenticationPrincipal User user){
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

您还可以创建自定义注释:

@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {}

查看详情here