Home > Software engineering >  polymorphic dto in a controller
polymorphic dto in a controller

Time:01-24

I have folowed this way to use polymorphic dto in a spring controller

https://bwgjoseph.com/polymorphic-dto-using-java-record-with-jackson

@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, defaultImpl = HomeAddressDto.class)
@JsonSubTypes({
    @Type(HomeAddressDto.class),
    @Type(OfficeAddressDto.class)
})
public interface Address {

}

public record HomeAddressDto(String street, String postalCode, String unit) implements Address {}

public record OfficeAddressDto(String building, String street, String postalCode, String unit) implements Address {}

That work well but in the controller

@RestController
@RequestMapping("/deduction/addresses")
public class DeductionAddressController {

    @PostMapping()
    public Address create(@RequestBody Address address) {
        if (address instanceof HomeAddressDto) {
            System.out.println("home");
        }

        if (address instanceof OfficeAddressDto) {
            System.out.println("office");
        }

        return address;
    }
}

instanceof is used, is there a way to avoid that?

CodePudding user response:

You can try to make abstract method in Address and then override it in subclasses.

Example: https://stackoverflow.com/a/3930848/11401122

CodePudding user response:

You could create a new service with similar polymorphism, for example

public class DeductionAddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping()
    public Address create(@RequestBody Address address) {
        addressService.processAddress(address);

        return address;
    }
}

where AddressService looks like

@Service
public class AddressServiceImpl implements AddressService {

   @Override
   public void processAddress(HomeAddressDto homeAddress) {
      System.out.println("home");
      // process HomeAddressDto...
   }

   @Override
   public void processAddress(OfficeAddressDto homeAddress) {
      System.out.println("office");
      // process OfficeAddressDto...
   }
}   
  • Related