Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Rest - How to receive Headers in @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) {
    ...
    ...
  }
}

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.

like image 391
Marcello de Sales Avatar asked Dec 21 '16 16:12

Marcello de Sales


1 Answers

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 :)

like image 134
Jens Schauder Avatar answered Nov 15 '22 04:11

Jens Schauder