• 请不要在回答技术问题时复制粘贴 AI 生成的内容
fuxinya
V2EX  ›  程序员

[Spring Boot] 表单如何绑定不同 POJO 对象

  •  
  •   fuxinya · Feb 19, 2019 · 2399 views
    This topic created in 2666 days ago, the information mentioned may be changed or developed.

    现在有三个 Goods 表单类

    • GoodsForm1
    • GoodsForm2
    • GoodsForm3

    均继承自GoodsFormGoodsForm里面存放的公用字段,各自则存放的独有字段。通过一个接口传入表单,能否自动识别绑定参数至Goods1Goods2Goods3

    public Object addGoods(@Validated GoodsForm goodsForm, BindingResult result) {
        if(goodsForm instanceof GoodsForm1) {
            // DO STH...
        }
    }
    

    还是说只能造三个接口。但是以后如果继续扩展怎么办,继续往下加感觉不优雅

    6 replies    2019-02-19 14:34:07 +08:00
    leon0903
        1
    leon0903  
       Feb 19, 2019
    没试过 但是感觉使用父类去绑定不同的子类是行不通的。
    fuxinya
        2
    fuxinya  
    OP
       Feb 19, 2019
    @leon0903 暂时的方案:不让 Spring 自动绑定了,手动用 JSON 工具去解析 body,根据 type 解析成不同的 GoodsForm。暂时先这样吧
    fuxinya
        4
    fuxinya  
    OP
       Feb 19, 2019
    fuxinya
        5
    fuxinya  
    OP
       Feb 19, 2019
    感谢 @smeraldo 的方案,已解决。不过项目里用的是阿里的 fastjson,可以使用 @JSONType 注解,支持 seeAlso 配置
    具体请参照文档 [JSONType_seeAlso_cn]( https://github.com/alibaba/fastjson/wiki/JSONType_seeAlso_cn)
    leon0903
        6
    leon0903  
       Feb 19, 2019
    我也长见识了 谢谢各位
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2917 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 15:06 · PVG 23:06 · LAX 08:06 · JFK 11:06
    ♥ Do have faith in what you're doing.