抽象类和Spring MVC @ ModelAttribute / @ RequestParam


问题内容

我的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
}

Jackson可以使用@JsonTypeInfo批注将JSON反序列化为特定的子类型。我希望Spring可以做同样的事情。


问题答案:

Jackson可以使用@JsonTypeInfo批注将JSON反序列化为特定的子类型。我希望Spring可以做同样的事情。

假设您使用Jackson进行类型转换(如果Spring在类路径上找到并且在<mvc:annotation- driven/>XML中存在,则Spring会自动使用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);
}