Call a specific constructor to map @requestBody

445 views Asked by At

I have a post call method and the method parameter is annotated with @ReuqestBody for class say A. Now, inside of my class A, there is a variable of type B and that class has couple of subclasses. In the request, I am passing enum for sub-type of B and want to intialize my requestBody based on the sub-type.

class A {
    B b;
    ...

    A(Subtype S, B data) {
         // I need to initialize A based on subtype (my B's class would be dynamic here)
    }
}

class B {
    String s1;
}

class C extends B {
    int x;
}

class D extends B {
    double d;
    String s2;
}


class XYZController {

    public Resp doThis (@RequestBody A, @PathVariable SubType) {

    }
}

enum SubType {
    C ("C")
    D ("D")
}

So the overall structure is something like this. Now, based on what I'm passing as subtype, I want to create that kind of object. I'm kind of confused on how Spring calls the constructors while doing such mappings. Any lead would really help.

Thanks a lot.

1

There are 1 answers

3
J. DEMARE On

Why not exposing every APIs available? I make sense to have specifics APIs and not a generic one.

it's the KISS pattern : Keep It Simple Stupid. It could allow you to enhance the affordance of your APIs.

Something like this :

@PostMapping(value="/mypath/v1/something-usefull-for-api-a")
public Resp doThis (@RequestBody A) {

}
@PostMapping(value="/mypath/v1/something-usefull-for-api-b")
public Resp doThisForB (@RequestBody B) {

}
@PostMapping(value="/mypath/v1/something-usefull-for-api-c")
public Resp doThisForC (@RequestBody C) {

}
...and so on...