在每个端点之前拦截 header 并调用服务

Intercept header & call service before every endpoint

我有一个用例,其中对我的 SpringBoot 应用程序的每个 HTTP 请求都将在 header 中包含一个 ID。我需要调用一个内部服务来根据该 ID 检索存储在我的数据库中的信息;这些信息将在 RestController 调用的我的服务中使用。

我考虑过使用拦截器,但即使它们允许我调用我的服务并检索数据库中的信息,但据我所知无法将 object 转发到我的业务服务。 我探索过的另一条路径是通过 AOP。但是,虽然您可以在方面内部检索调用您的方法的信息,但我认为您不能访问注释方法内部的方面检索的数据。

有没有什么方法可以在不使用 @RequestHeader 并在每个 RestController 方法中手动调用我的服务的情况下正确执行此操作(从而重复大量代码)?

谢谢!

but even though those will allow me to call my service and retrieve informations in the DB, there's no way in my knowledge to forward that object to my business services

您可以使用具有 http 请求范围的 HttpServletRequest request,这意味着为客户端在服务器中发出的每个 http 请求创建一个新对象。您可以通过每个拦截器用其他信息丰富它,以便在将其传递给最终控制器方法时将其作为属性包含。

使用 HandlerInterceptor 的以下方法,该方法将在调用 spring 业务方法之前调用。

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

然后在此方法中,您可以将您想要的值设置为请求对象中的属性。

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    ... call external api and fetch some value....
    ... Object myObj = apiCall...
    request.setAttribute("myObj", myObj);
    return true;
}

然后在您的 spring 控制器中您可以访问您之前设置的这个属性。

    @GetMapping(path = "/{mypath}")
    public void getRequest(HttpServletRequest request){

       Object myObj = request.getAttribute("myObj");
        if (myObj != null) {
          //you have myObj accessible here!
        }
   }