lundi 6 avril 2015

Spring MVC. Default values for fields of method parameter

I have a simple controller with method test:



@RequestMapping(produces = "application/json")
@ResponseBody
public HttpEntity<Void> test(Test test) {
return new ResponseEntity<>(HttpStatus.OK);
}


Test class looks like this:



public class Test {
private String name;
private Date date;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Date getDate() {
return date;
}

@DateTimeFormat(iso= DateTimeFormat.ISO.DATE)
public void setDate(Date date) {
this.date = date;
}
}


And I need default values for fields of Test object. If I had a primitive param, I would be able to use @RequestParam(required = false, defaultValue = "someValue"). But with non-primitive param this approach doesn't seem to work. I see a couple of variants how to deal with it:



  • Assign values in a constructor. Not very good, because may be I will need different defaults for different methods.

  • Write custom DataBinder. Better, but the problem with different defaults still exists.

  • Write custom DataBinder and custom annotation with defaults.


Am I missing something and there is a built in feature which can solve my problem?


Aucun commentaire:

Enregistrer un commentaire