我正在开发一些社交系统,我想做一些注释,自动将loggingUser注入(inject)到方法参数中。
我尝试过使用 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
}
是否可以使用方面和注释来做到这一点,或者我应该寻找其他解决方案?
最佳答案
有一个@AuthenticationPrincipal
,它适用于 Controller 方法参数。请参阅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
关于java - Spring通过注解为当前用户传递参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376005/