简体   繁体   English

Spring MVC-用于继承层次结构的REST端点

[英]Spring MVC - REST endpoint for inheritance hierarchy

I'm using a JOINED inheritance strategy for a class hierarchy which as follows: 我正在为类层次结构使用JOINED继承策略,如下所示:

abstract super class Product

concrete sub class Type1Product extends Product

concrete sub class Type2Product extends Product

Now i want to make a REST endpoint which allows users to POST data and for it to be parsed as a specific subclass of product, making sure its the same endpoint for any type of product. 现在,我想创建一个REST端点,该端点允许用户发布数据,并将其解析为产品的特定子类,并确保它对于任何类型的产品都具有相同的端点。 So something like the following: 因此,如下所示:

@RequestMapping(method = POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Product save(@Valid Product product) {
        // ...
        return product;
    }

Currently when I try to post I get an error saying I can't initialize an abstract class, since Spring is trying to create a Product instance as opposed to an instance of the correct subtype. 当前,当我尝试发布时,我收到一条错误消息,提示我无法初始化抽象类,因为Spring试图创建一个Product实例,而不是正确的子类型的实例。

Is what I'm trying to do possible? 我想做的事可能吗? If not then what is the best practice or convention when making endpoints like this for an inheritance hierarchy? 如果不是,那么在为继承层次结构创建这样的端点时,最佳实践或惯例是什么?

let us see what you are trying to do, you are trying to deserialize an object and you are telling jackson that its Product which is your abstract class, and you want jackson to find by itself what the concrete class. 让我们看看您要做什么,正在尝试反序列化一个对象,并告诉jackson它的Product是您的抽象类,并且您希望jackson自己找到具体的类。

this could not be achieved and it make sense , lets say jackson could be built to figure out what which concrete class based on the additional attributes, ok so suppose we have two concrete classes with no additional attributes, here how jackson gonna find out what is the concrete class? 这是无法实现的,并且说得通,可以说杰克逊可以根据附加属性来找出哪个具体类,好吧,所以假设我们有两个没有附加属性的具体类,杰克逊将如何找出这是什么具体的课程?

when specifying the deserialized class default constructor will be called so if your class is abstract that will not work, you need an endpoint for each concrete class or you need a DTO and model mapper, your DTO can contain the concrete class and all the possible attributes and your model mapper should rely in the concrete class indicated in your DTO, using this approach you can do it in one endpoint. 当指定反序列化的类时,将调用默认构造函数,因此,如果您的类是抽象类,将不起作用,则需要每个具体类的终结点,或者需要DTO和模型映射器,DTO可以包含具体类和所有可能的属性并且您的模型映射器应该依赖于DTO中指示的具体类,使用这种方法,您可以在一个端点中完成此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM