Answer the question
In order to leave comments, you need to log in
How to make two methods per endpoint in a Spring REST controller?
I have several roles and one endpoint. Faced such a situation that each role needs its own set of parameters. Well, for example, there is a CONSUMER role and there is a PRODUCER role . And there is an endpoint that both roles have access to:
@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
@RequestParam(value = "consumer-region-code") Integer regionCode,
@AuthenticationPrincipal AuthorizedUser user) {
...
}
consumerId
and is needed regionCode
, but the principal is not needed. Because of this, the method grows very much, each role brings something new. Ideally, it would be to make two separate methods on one endpoint:@PostMapping("/order")
public void pay(@AuthenticationPrincipal AuthorizedUser user) {
...
}
@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
@RequestParam(value = "consumer-region-code") Integer regionCode) {
...
}
Answer the question
In order to leave comments, you need to log in
Why not instead:
@PostMapping("/order")
public void pay(@AuthenticationPrincipal AuthorizedUser user) {
...
}
@PostMapping("/order")
public void pay(@RequestParam(value = "consumer-id") Integer consumerId,
@RequestParam(value = "consumer-region-code") Integer regionCode) {
...
}
@PostMapping("/order")
public void pay(
@AuthenticationPrincipal AuthorizedUser user,
@RequestParam(value = "consumer-id", required = false) Integer consumerId,
@RequestParam(value = "consumer-region-code", required = false) Integer regionCode
) {
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question