在 java 中创建一个包装器 class 接受函数

create a wrapper class accepting function in java

我想制作一个包装器 class,它可以进行预处理,执行传递的函数,然后在返回响应之前进行一些 post 处理。 我如何编写包装器 class 来接受函数作为参数并调用它?

@Autowired
private SomeService service;

@GetMapping("/path")
public CustomResponse(CustomRequest request){
  1. preprocess(request)
  2. CustomResponse response = service.functionA(request)
  3. postprocess(response)
  4. return response;
------------------------- vs --------------------------------
  1. return CustomWrapper.execute(request,???,response)
}

-- **Need help in writing this class.**

class CustomWrapper{
  void preprocess();
  ?? execute();
  void postprocess();
}

这基本上应该是您要查找的内容,如果您愿意,可以对后处理器和预处理器进行硬编码,以便像您的示例一样使用它,但这有点更笼统:

public class CustomProcessor {

    private Function<CustomRequest, CustomRequest> preprocessor;
    private Function<CustomResponse, ResponseEntity<CustomResponse>> postprocessor;

    public CustomProcessor(
            Function<CustomRequest, CustomRequest> preprocessor,
            Function<CustomResponse, ResponseEntity<CustomResponse>> postprocessor
    ) {
        this.preprocessor = preprocessor;
        this.postprocessor = postprocessor;
    }

    public ResponseEntity<CustomResponse> execute(CustomRequest request, Function<CustomRequest, CustomResponse> processor) {
        request = preprocessor.apply(request);
        CustomResponse response = processor.apply(request);
        return postprocessor.apply(response);
    }

}

在@void void 的帮助下,答案能够按要求实现。

public class ControllerTemplate<Req, Res> {

  private static final Logger logger = LogManager.getLogger(ControllerTemplate.class);

  public Res execute(Req req, Function<Req, Res> processor) {
    preProcess(req);
    Res res = processor.apply(req);
    postProcess(res);
    return res;
  }

  private void postProcess(Res res) {
    logger.info("response body: {}", res);
  }

  private void preProcess(Req req) {
    logger.info("request body: {}", req);
  }
}

调用函数

 @GetMapping("/logLevel")
  public String updateLogLevel(@RequestParam String level) {
    return new ControllerTemplate<String, String>()
        .execute(level, req -> log4jService.changeLogLevel(req));
  }