juanmorschrott
juanmorschrott

Reputation: 603

Is it considered a good practice using classes that extend an abstract class as @RequestBody?

I´m working on a legacy spring boot project that makes a strong reuse of a DTO class in a generic controller and in multiple services:

@PostMapping
controller.input(@RequestBody MyTypeDto type) { ... }

service.resolve(MyTypeDto type) { ... }

processor.send(MyTypeDto type) { ... }

I want to start decoupling it by creating another endpoint and making MyTypeDto an abstract class. My biggest concern under all is the compatility with jackson.

public abstract class MyTypeDto { ... }

public class AnotherTypeDto extends MyTypeDto { ... }

public class AndAnotherTypeDto extends MyTypeDto { ... }

Is it considered a good practice?

Upvotes: 1

Views: 627

Answers (1)

  • As it is implied on your question, you controller endpoint is generic, it takes the input, creates the type, pass it to service based on subtype. Otherwise, you will end up many endpoints which all doing is creating the subtype and pass it to service.

  • If Jackson is your concern, Jackson has mechanism for subtypes. Please note you have to send one additional field which act as the discriminator (in this example, it is called type to decide which sub type to create.

    @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type")
    @JsonSubTypes({@JsonSubTypes.Type(value = FirstSubDto.class, name = "First"),
                 @JsonSubTypes.Type(value = SecondSubDto.class, name = "Second")})
    public abstract class MyTypeDto {
    
      ..

    }

Upvotes: 1

Related Questions