Eng*_*_DJ 10 java inheritance binding spring-mvc jackson
我的Spring/Hibernate应用程序中有一个模型类层次结构.
在向Spring MVC控制器提交POST表单时,是否有任何标准方法来指定所提交对象的类型,因此Spring可以实例化接收方法的@ModelAttribute或@RequestParam中声明的类型的正确子类?
例如:
public abstract class Product {...}
public class Album extends Product {...}
public class Single extends Product {...}
//Meanwhile, in the controller...
@RequestMapping("/submit.html")
public ModelAndView addProduct(@ModelAttribute("product") @Valid Product product, BindingResult bindingResult, Model model)
{
...//Do stuff, and get either an Album or Single
}
Run Code Online (Sandbox Code Playgroud)
Jackson可以使用@JsonTypeInfo注释将JSON反序列化为特定子类型.我希望Spring能做同样的事情.
Jackson可以使用@JsonTypeInfo注释将JSON反序列化为特定子类型.我希望Spring能做同样的事情.
假设您使用Jackson进行类型转换(如果Spring在类路径中找到它并且您使用<mvc:annotation-driven/>XML,则自动使用Jackson ),那么它与Spring无关.注释类型,Jackson将实例化正确的类.不过,您必须instanceof在Spring MVC控制器方法中进行检查.
评论后更新:
查看15.3.2.12自定义WebDataBinder初始化.您可以使用@InitBinder基于请求参数注册编辑器的方法:
@InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
String productType = request.getParam("type");
PropertyEditor productEditor;
if("album".equalsIgnoreCase(productType)) {
productEditor = new AlbumEditor();
} else if("album".equalsIgnoreCase(productType))
productEditor = new SingleEditor();
} else {
throw SomeNastyException();
}
binder.registerCustomEditor(Product.class, productEditor);
}
Run Code Online (Sandbox Code Playgroud)