0

In my web project I'd like to use different specific command objects inheriting from the same abstract base class. Something like:

public abstract BaseDTO {
    public String id;
    public String name;

    //...
}

public ADTO extends BaseDTO {
    public String address;

    //...
}

public BDTO extends BaseDTO {
    public String phone;

    //...
}

and so on...

At the moment I'm using several methods in my controller to handle each concrete command object, but it's quite annoying. I'd like to use a single method:

@PostMapping("/submit")
public String submit(@Valid @ModelAttribute("myAttribute") BaseDTO dto, BindingResult result) {
    // ...
}

Is there a way to achieve this?

davioooh
  • 23,742
  • 39
  • 159
  • 250

1 Answers1

0

Without knowing the context If you really want only one endpoint, my solution would be to create a one DTO like your BaseDTO, put all the parameters there and make some of them Optional. So you will have one Endpoint with all the data you need, and then you'll be able to process the data based on fields you receive.

public SubmitDTO {
    public String id;
    public String name;
    public Optional<String> address = Optional.empty();
    public Optional<String> phone = Optional.empty();
    //...
}

But I suggest you think twice, whether the idea of one common endpoint is good. Because from business domain perspective it's quite strange that you will have one endpoint for everything that happens on your client side. It could be very hard to maintain such code in the future.

And If you really really need your scenario, then you could take a look at the answer in this thread: Spring @ReponseBody @RequestBody with abstract class

Community
  • 1
  • 1