How instantiate a concrete class in init binder?

限于喜欢 提交于 2019-12-11 05:08:54

问题


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);
    }
}

回答1:


@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 .

public class CommandObject {

    private AbstractObj type;

    public void setType(AbstractObj type) {
        this.type = type;
    }

}


来源:https://stackoverflow.com/questions/21550238/how-instantiate-a-concrete-class-in-init-binder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!