如何实例化init binder中的具体类?

时间:2014-02-04 10:45:39

标签: java spring spring-mvc model-binding

我必须将抽象类绑定到我的控制器请求处理程序方法。

在使用@ModelAttribute带注释的方法实例化具体类之前:

@ModelAttribute("obj")
public AbstractObh getObj(final HttpServletRequest request){
    return AbstractObj.getInstance(myType);     
}

但是现在我尝试在没有@ModelAttribute注释方法的情况下执行此操作,因为每次调用控制器都会触发模型属性注释方法。

所以我尝试使用 InitBinder 自定义编辑器获得具体课程,但它不起作用。

My Init Binder:

@InitBinder(value="obj")
protected void initBinder(final WebDataBinder binder) {
    binder.registerCustomEditor(AbstractObj.class, new SchedaEditor());
}

我的帖子处理程序

@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("obj") AbstractObj obj, final BindingResult bindingResult) {
    //my handler
    }

这是我的 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 个答案:

答案 0 :(得分:0)

@ModelAttribute只是一个命令对象。根据请求参数,它不打算具有variuos实现。 WebDataBinder只会影响所有参数映射到命令字段的方式。 所以 - 使用AbstractObj类型的字段创建简单的命令对象。

public class CommandObject {

    private AbstractObj type;

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

}