Home > Software design >  Is there a way to declare a default value in a @RequestBody field similar to defaultValues in @Reque
Is there a way to declare a default value in a @RequestBody field similar to defaultValues in @Reque

Time:07-14

We have this request body which is supposed to map query params when an endpoint is accessed

public class RetrieveTxnRequest {

  private Short pageStart = 0;

  private Short pageSize = Short.MAX_VALUE;
}

But when we call the endpoint like this:

serverUrl/ourEndpoint?pageSize=

pageSize is set to null. If we supply a value it works. I noticed that if instead of using a class we use @RequestParams, the problem does not occur:

@GetMapping("/ourEndpoint")
public OurResponse getTransactions(@RequestParam(required = false, defaultValue = "0") Short pageStart,
                                   @RequestParam(required = false, defaultValue = "50") Short pageSize) 

because default values are set.

I tried the ff:

public class RetrieveTxnRequest {

  private Short pageStart = 0;

  @Value("50")
  private Short pageSize = Short.MAX_VALUE;
}

But it doesn't seem to work, pageSize is still null if we use the endpoint mentioned above

tldr: Is there a way to set default values in Spring @RequestBody classes?

CodePudding user response:

use nulls=Nulls.SKIP

@JsonSetter(nulls = Nulls.SKIP)
private Short pageSize = 50;

CodePudding user response:

You can set the value in the class and it will be treated as a default value.

public class RetrieveTxnRequest {

  private Short pageStart = 0;

  private Short pageSize = "default_value";
}

Also refer to the link for this response

  • Related