如何在 Spring MVC 4.3 中设置 FORM 绑定以在控制器中具有继承树的适当子对象

Thr*_*ion 7 spring spring-mvc spring-mvc-initbinders spring-form

我正在对一个非常旧的应用程序进行更改。这是使用 Spring MVC 4。

我需要在 Spring 控制器的 JSP 中从 form:form 标签中发布数据。UI 是固定的,我只能在服务器端进行更改。基于我提交的表单中的特定字段,我希望在我的 Controller Handler 方法参数中有正确的子对象实例。

例如,

class Payment {...}
class CardPayment extends Payment{...}
class CheckPayment extends Payment{...}
Run Code Online (Sandbox Code Playgroud)

在 UI 表单中,会有一个名为 paymentType 的输入值。付款将是 commandObject 或 ModelAttribute

我希望我的 @PostMapping 控制器在参数中具有正确的子对象。我不想在控制器代码中手动实例化它。

@PostMapping
public ModelAndView doSomePay(@ModelAttribute("payment") Payment paymentInput, BindingResult result){
Run Code Online (Sandbox Code Playgroud)

现在我希望paymentInput上面的这个对象是 CardPayment 或 checkPayment 类型。

我试图创建一个@initBinder and WebDatabinder但实际上我有近 10 个子类,我是否需要为所有这些创建“编辑器”?

如果是,那么短而快速地创建 propertyEditor 的最佳方法是什么

@InitBinder
    public void initBinder(WebDataBinder binder, HttpServletRequest request) {
        String paymentType = request.getParameter("paymentType");

        PropertyEditor productEditor;
       //somehow I can find the correct child class that I need to see, for example CardPatment.class ,  Now how to do following 

       binder.set(Product.class,productEditor); ???
}
Run Code Online (Sandbox Code Playgroud)