gpt4 book ai didi

java - 将主体绑定(bind)到 MyCustomUser 类作为 Controller 中的方法参数

转载 作者:行者123 更新时间:2023-12-02 10:07:38 24 4
gpt4 key购买 nike

我知道您可以通过包含 Principal 作为方法参数,在 Spring Controller 中轻松获取用户名,如下所示:

@GetMapping("/username")
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}

但我最终想要访问 MyCustomUser 类的成员,该类是我使用 findBy 方法从存储库实例化的。我可以在 Controller 中放置一个辅助方法来进行查找并根据 principal.getName() 返回用户,但是我可以更进一步并绑定(bind)到 MyCustomUser 直接,如

@GetMapping("/stuff")
@ResponseBody
public String stuff(MyCustomUser user) {
return user.thing();
}

我正在考虑创建一个像( Ref )这样的转换器:

@Component
public class PrincipalToMyCustomUserConverter implements Converter<Principal, MyCustomUser> {

private MyCustomUserRepository userRepository;

public PrincipalToApplicationUserConverter(MyCustomUserRepository userRepository) {
this.userRepository = userRepository;
}

@Override
public MyCustomUser convert(Principal source) {
return this.userRepository.findByUsername(source.getName());
}

}

但我不知道这是否是获取存储库的适当方法,并且我不知道在注册转换器时如何传递存储库( Ref )。

最佳答案

您是对的,您建议的转换器不合适。您的转换器可以从 Principal 类型的对象转换为 MyCustomUser 类型的对象,但是,没有 *Principal* 可供转换。主体注入(inject)背后的魔力在于 Spring 实际上从 SecurityContextHolder 获取它,它不是从请求中反序列化的......尽管请求中存在的字段允许 Spring 创建主体>。如果您确实想注入(inject)MyCustomUser,请使用ModelAttributeModelAttributes 可用于所有 Spring Controller 方法。

我通常喜欢将这样的东西保留在它自己的类中,因此我会定义一个类,将这个和其他 @ControllerAdvice 保存在一个地方,如下所示:

@ControllerAdvice
public class SomeControllerAdvice {
@Autowired
private MyCustomUserRepository myCustomUserRepository;

@ModelAttribute
public MyCustomUser getUser(Principal principal) {
return myCustomUserRepository.findByUsername(principal.getName());
}
}

以上内容足以使 MyCustomUser 可用于所有方法。我要指出的是,您可能需要在这里进行一些错误处理,例如如果主体为 null 则跳过等等,还让您的 findByUsername 方法返回一个可选,以便您可以解决空返回问题。

参见: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

关于java - 将主体绑定(bind)到 MyCustomUser 类作为 Controller 中的方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com