问题描述
我必须将抽象类绑定到我的控制器请求处理程序方法.
I have to bind an abstract class to my controller request handler method.
在我使用@ModelAttribute
带注释的方法实例化具体类之前:
Before I instantiate the concrete class with @ModelAttribute
annotated method:
@ModelAttribute("obj")
public AbstractObh getObj(final HttpServletRequest request){
return AbstractObj.getInstance(myType);
}
但是现在我尝试在没有@ModelAttribute
注释方法的情况下执行此操作,因为每次调用控制器触发器模型属性注释方法也是如此.
But now I try to do that without the @ModelAttribute
annotated method, beacause every call to controller trigger model attribute annotated method too.
因此,我尝试使用 InitBinder 和自定义编辑器来获得具体的类,但这是行不通的.
So I try to get concrete class with InitBinder and a custom editor, but it doesn't work.
我的Init活页夹:
@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);
}
}
推荐答案
@ModelAttribute只是命令对象.它不打算具有依赖于请求参数的各种实现.WebDataBinder仅影响如何将所有参数映射到命令字段.因此,请创建一个类型为AbstractObj的简单命令对象.
@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;
}
}
这篇关于如何在初始化绑定器中实例化具体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!