Spring Data Rest – 如何在@RepositoryEventHandler中接收标头

我正在使用最新的Spring Data Rest,我正在“创建之前”处理该事件.我的要求是捕获提交给模型“Client”的POST端点的HTTP Headers.但是,RepositoryEventHandler的接口不会公开它.

@Component
@RepositoryEventHandler
public class ClientEventHandler {

  @Autowired
  private ClientService clientService;

  @HandleBeforeCreate
  public void handleClientSave(Client client) {
    ...
    ...
  }
}

我们如何处理事件并捕获HTTP标头?我想访问像Spring MVC这样使用@RequestHeader HttpHeaders标头的参数.

最佳答案
您只需将请求自动装配到EventHandler的字段即可

@Component
@RepositoryEventHandler
public class ClientEventHandler {
    private  HttpServletRequest request;

    public ClientEventHandler(HttpServletRequest request) {
        this.request = request;
    }

    @HandleBeforeCreate
    public void handleClientSave(Client client) {
        System.out.println("handling events like a pro");
        Enumeration<String> names = request.getHeaderNames();
        while (names.hasMoreElements())
            System.out.println(names.nextElement());
    }
}

在给出的代码中,我使用了构造函数注入,我认为它是最干净的,但Field或Setter注入应该也能正常工作.

我实际上在stackoverflow上找到了解决方案:Spring: how do I inject an HttpServletRequest into a request-scoped bean?

哦,我刚注意到@Marc在评论中提出了这个…但我实际上尝试过:)

转载注明原文:Spring Data Rest – 如何在@RepositoryEventHandler中接收标头 - 代码日志