给定 Spring-MVC Controller 中的“保存”方法:
@RequestMapping(value = "/save")
public void save(@ModelAttribute(MY_KEY) final MyModel myModel) { ... }
myModel
参数中的属性是一个抽象类:
public class MyModel {
public AbstractFruit fruit;
}
是否有任何方法可以在请求中指定使用特定子类(例如 Apple
)?
最佳答案
您可以在 Controller 类中使用自定义 init binder 方法:
// Additionally using MY_KEY as "value" parameter of this annotation
// is not working in some cases
@InitBinder
public void initBinder(WebDataBinder webDataBinder, HttpServletRequest servletRequest) {
// Probably you only want to init this when form is submitted
if (!"POST".equalsIgnoreCase(httpServletRequest.getMethod()) {
return;
}
// Filter out all request when we have nothing to do
Object nonCastedTarget = webDataBinder.getTarget();
if (nonCastedTarget == null || !(nonCastedTarget instanceof MyModel)) {
return;
}
MyModel target = (MyModel) nonCastedTarget;
if (/* some condition */) {
target.setFruit(new Apple());
} else {
target.setFruit(new Banana());
}
}
Spring 表单绑定(bind)机制将正确设置 Apple/Banana 类中的所有字段。
关于java - 如何在Spring-MVC方法中绑定(bind)抽象类的子类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21531860/