java - Spring通过注解为当前用户传递参数值

标签 java spring annotations parameter-passing

我正在开发一些社交系统,我想做一些注释,自动将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/

相关文章:

hibernate - 可嵌入在实体中使用两次的自定义 UserType

java - 如何使用基于组的@Validated 注释验证方法参数

spring - 内容类型为 application/x-www-form-urlencoded 的 @RequestParam 在 Spring Boot 2.2 中不起作用

java - OpenCSV 未使用注释映射 JavaBean

java - 用于 spring 和 hibernate 应用程序的虚拟主机

java - Spring Security 具有自定义 AuthenticationProvider 自定义用户详细信息和自定义安全上下文

java - 没有带有@Deprecated 注释的编译警告?

java - 如何在java中创建网页的哈希值?

java - 如何将 Or 与 JUnit 假设一起使用

java - 缩小 JFrame 会导致绘图消失;靶心边框不显示