Search code examples
javaspringspring-bootannotationsspring-annotations

How to set default value on field values in a class used in spring boot request parameter


I am creating a GetEndpoint exposed like below

@GetMapping
public void someMethod(@RequestParam(value = "selectedColor", required = false, 
                          defaultValue = "WHITE") Color seletedColor) {

....

}

I need to convert all method parameters to a class object like below. Please let me know how to set default value defaultValue = "WHITE" at field level in below class

@GetMapping
public void someMethod(RequestParameter request) {

....

}

public Class RequestParameter {
    // How to set default value if parameter is null
    private Color seletedColor;
}

Solution

  • I would suggest using a getter to have this logic. For example:

    public class RequestParameter {
       ...
    
       public Color getSelectedColor() {
          return Optional.ofNullabe(selectedColor).orElse(Color.WHITE);
       }
    
    }