Spring Data Rest - How to receive Headers in @RepositoryEventHandler

谁都会走 提交于 2019-12-21 05:25:09

问题


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) {
    ...
    ...
  }
}

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.


回答1:


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());
    }
}

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

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

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



来源:https://stackoverflow.com/questions/41267602/spring-data-rest-how-to-receive-headers-in-repositoryeventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!