Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 MVC - Rest service - use default values in beans

I am using Spring 4.1.4 and implementing a simple REST service. I do have a POST method which gets a Person object as request.

@ResponseStatus(value = HttpStatus.CREATED)
@RequestMapping(value = "", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public void add(@Valid @RequestBody Person oPerson) throws Exception {
    //do the things
}

Bean:

public class Person {

    public Person(){ }

    private String firstname;

    private String lastname;

    private Integer activeState;

    //getter+setter
}

My question is - is there a possibility to set a default value for the properties in the bean. Something like this:

@Value(default=7)
private Integer activeState;

I know when using the @RequestParam annotation in a @RestController methode it is possible to set a default value with @RequestParam(value="activeState", required=false, defaultValue="2") but is there a possibility to do a similar thing on class level?

like image 419
K.E. Avatar asked Feb 19 '16 07:02

K.E.


1 Answers

Your Person class is not really a spring bean. It is simply a class whose parameters are set when you make a call to your application endpoint due to the @RequestBody annotation. The parameters which are not in the body of your call will simply not get binded so to solve your problem you can do this:

  1. Set default values for your person class like this (toString() is overridden for convenience:

    public class Person {
    
        public Person() {
        }
    
        private String firstName = "default";
        private String lastName = "default";
        private Integer activeState = 7;
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public Integer getActiveState() {
            return activeState;
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    ", activeState=" + activeState +
                    '}';
        }
    }
    
  2. Perform the request to your endpoint, for example with this json data:

    {
        "firstName": "notDefault"
    }
    
  3. If you print out the person object in your controller, you'll notice that the firstName got the non-default value while others are default:

    public void add(@Valid @RequestBody Person oPerson) {
        System.out.println(oPerson);
    }
    

Console output: Person{firstName='notDefault', lastName='default', activeState=7}

like image 120
Edd Avatar answered Oct 14 '22 00:10

Edd