I have to bind an abstract class to my controller request handler method.
Before I instantiate the concrete class with @ModelAttribute
annotated method:
@ModelAttribute("obj")
public AbstractObh getObj(final HttpServletRequest request){
return AbstractObj.getInstance(myType);
}
But now I try to do that without the @ModelAttribute
annotated method, beacause every call to controller trigger model attribute annotated method too.
So I try to get concrete class with InitBinder and a custom editor, but it doesn't work.
My Init Binder:
@InitBinder(value="obj")
protected void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(AbstractObj.class, new SchedaEditor());
}
And My Post Handler:
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("obj") AbstractObj obj, final BindingResult bindingResult) {
//my handler
}
This is my ObjEditor:
@Override
public void setAsText(final String text) throws IllegalArgumentException {
try{
if(text == null){
setValue(new ConcreteObj());
}else{
setValue(objService.findById(Long.valueOf(text)));
}
}catch(Exception e) {
setValue(null);
}
}
@ModelAttribute is just a command object. It is not intended to have variuos implementations depending on request parameters. WebDataBinder just influences how all parameters are being mapped to command fields. So - create simple command object with field of type AbstractObj .