Springboot, there is an abstract member in the request model, how can I configure it to be instantiated correctly?

background:
there is a member variable f in the model (Request) that receives client requests, which needs to be instantiated into different instances (An or B) for different business types (type).

    public abstract class Father {
    }
    public class A extends Father {
        private String a1;
        private String a2;
    }
    public class B extends Father {
        private String b1;
        private String b2;
    }
    public class Request {
        private Father f;
        private String type; // typefAB
    }

the current solution is to receive it directly with a JSONObject in the request model, and then convert it to a concrete instance.

public class Request {
    private JSONObject f;
    private String type; // typefAB
}

excuse me, how to configure (or how to do) in springboot so that the code of json- > A can be omitted? I cast it directly into a concrete instance in the rest of the business.
or is there any other better solution to deal with similar problems?

Thank you all for your generous advice.

Apr.06,2022

if the decision is based on the request parameters, you can write a custom parameter parser:

  @ zzzzbw  similarly, your business logic framework will not support it so well, you can write your own logic processing. 
secondly, your design is a little strange, if they are two objects, encapsulated into two interfaces, two entities would be fine. If it is a derivative of a parent class, but the type is different, it can be used directly in an object, and the database can also use a table.
so you can think about your own design issues.

< hr >

the editor is the owner of Subscription account's "code craftsman's notes". He has worked for ThoughtWorks, Alibaba and other Internet companies to share his experience, including but not limited to JAVA, concurrent programming, performance optimization, architecture design, Mini Program, open source software, etc. If you are interested, you can follow the wave, study and discuss together.

Menu