Spring Data Rest-如何在@RepositoryEventHandler中接收标头 [英] Spring Data Rest - How to receive Headers in @RepositoryEventHandler

查看:242
本文介绍了Spring Data Rest-如何在@RepositoryEventHandler中接收标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新的Spring Data Rest,并且正在处理事件"创建前".我的要求是还要捕获提交给模型"客户端"的 POST 端点的HTTP标头.但是, RepositoryEventHandler 的接口不会公开该信息.

I'm using the latest Spring Data Rest and I'm handling the event "before create". The requirement I have is to capture also the HTTP Headers submitted to the POST endpoint for the model "Client". However, the interface for the RepositoryEventHandler does not expose that.

@Component
@RepositoryEventHandler
public class ClientEventHandler {

  @Autowired
  private ClientService clientService;

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

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

How can we handle events and capture the HTTP Headers? I'd like to have access to the parameter like Spring MVC that uses the @RequestHeader HttpHeaders headers.

推荐答案

您可以简单地将请求自动关联到EventHandler的字段

You can simply autowire the request to a field of your 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注入也应该可以正常工作.

In the code given I used Constructor Injection, which I think is the cleanest, but Field or Setter injection should work just as well.

我实际上找到了关于stackoverflow的解决方案:

I actually found the solution on stackoverflow: Spring: how do I inject an HttpServletRequest into a request-scoped bean?

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

Oh, and I just noticed @Marc proposed this in thecomments ... but I actually tried it :)

这篇关于Spring Data Rest-如何在@RepositoryEventHandler中接收标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆