首页 > 解决方案 > Spring - 返回端点的字符串结果并将其存储在变量中

问题描述

这是我的端点,登录后它会返回我的电子邮件地址

@GetMapping("/user")
public String userInfo(Authentication authentication) {
    String userName = authentication.getName();
    return userName;
}

我想给createdBy变量这个值

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(InsertTheNewStringVariableHere);
    return requestUseCase.createRequest(requestDTO);
}

标签: javaspringspring-boot

解决方案


这一切都取决于您如何访问您的rest api.

如果你拥有代码,我的意思是如果你的类在同一个项目中,你可以这样做:

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(yourServiceInstance.userInfo(authentication));
    return requestUseCase.createRequest(requestDTO);
}

如果它是 external api,您将不得不从 a 调用该服务http client

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(yourHttpClient.callUserInfo(authentication));
    return requestUseCase.createRequest(requestDTO);
}

你将在你的类中注入你的userInfo对象和一个Authentication对象。


推荐阅读