gpt4 book ai didi

java - 使用 Spring Boot 将 header 参数反序列化为 POJO

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

作为我的 REST API 的一部分,我需要访问存储在 Authorization header 中编码的 Operator。

我可以这样访问:

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Customer post(@RequestBody CustomerRequest request, @RequestHeader(name = "Authorization") String authorization) {
// Some logic to parse the authorization header here which gets duplicated in every REST method
Operator operator = parseAuthorization(authorization);
}

但是这有点尴尬,并且每次使用时都需要大量重复代码。

有没有办法可以使用自定义注释和某种形式的中间件来做到这一点,例如:

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Customer post(@RequestBody CustomerRequest request, @Operator Operator operator) {
}

最佳答案

这可以使用 Spring Converters 来完成,例如

@Component
public class OperatorHeaderConverter implements Converter<String, Operator> {

private final AuthenticationService service;

@Autowired
public OperatorHeaderConverter(AuthenticationService service) {
this.service = service;
}

@Override
public Operator convert(String source) {
return service.parseAuthorization(source);
}
}

配置使用:

@Configuration
public class ControllerConfiguration extends WebMvcConfigurerAdapter {

private final OperatorHeaderConverter operatorHeaderConverter;

@Autowired
public ControllerConfiguration(OperatorHeaderConverter converter) {
this.operatorHeaderConverter = converter;
}

@Override
public void addFormatters (FormatterRegistry registry) {
registry.addConverter(operatorHeaderConverter);
}

}

并在 Controller 中使用,例如:

@RequestMapping(method = RequestMethod.GET, produces = "application/json")
public List<CustomerResponse> getCustomers(@RequestHeader(name = "Authorization") Operator operator) {
// Do something with the operator
}

关于java - 使用 Spring Boot 将 header 参数反序列化为 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45848385/

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