如何创建用于将HTTP标头转换为自定义dto的拦截器?

在我的一个应用程序中,我有许多端点具有相同的标头集:

@RequestHeader("foo") String foo,
@RequestHeader("bar") String bar,
@RequestHeader("baz") String baz,

在每种控制器方法中,我都基于这些标头创建我的自定义dto:

MyDto myDto = new MyDto(foo, bar, baz);

To avoid duplicates and adding/removing one header 50 times to each method, I want to have something like interceptor class that will take HttpHeaders and will transform it MyDto only once, so then I want to be able to replace all request headers in controller methods by simply MyDto myDto created behind the scenes.

我试图找到解决方案,但没有发现任何东西。

实际:

@PostMapping("/myEndpoint")
public MyResponse myEndpoint(@RequestHeader("foo") String foo,
                             @RequestHeader("bar") String bar,
                             @RequestHeader("baz") String baz,
                             @RequestBody MyRequest myRequest) {

    MyDto myDto = new MyDto(foo, bar, baz);
    myService.doSomething(myDto);

    ...
}

预期:

@PostMapping("/myEndpoint")
public MyResponse myEndpoint(MyDto myDto,
                             @RequestBody MyRequest myRequest) {

    myService.doSomething(myDto);

    ...
}

我也有一个方法:

public MyDto transform(HttpHeaders httpHeaders) {

    String foo = getHeader(httpHeaders, "foo");
    String bar = getHeader(httpHeaders, "bar");
    String baz = getHeader(httpHeaders, "baz");

    return new MyDto(foo, bar, baz);
}

private String getHeader(HttpHeaders httpHeaders,
                         String key) {

    return Optional.ofNullable(httpHeaders.get(key))
                   .map(Collection::stream)
                   .orElseGet(Stream::empty)
                   .findFirst()
                   .orElse(null);
}

但是我不知道何时可以调用它以使其在每个请求中都可运行。

评论