Reputation: 131
I have got PaymentTransactionDTO as superclass and subclasses like PhoneBillPaymentTransactionDTO which has a field as phoneNumber etc.
and I would like to handle these DTOs from single payment service. My controller method like below;
public ResponseEntity<TransactionStatus> payment(@PathVariable String accountNumber,
@Valid @RequestBody PaymentTransactionDTO paymentTransactionDTO)
When I post PhoneBillPaymentTransactionDTO to the method above, I can't reach phoneNumber field as I have PaymentTransactionDTO in the method signature.
How should I have a design to manage multiple inherited dtos from single method ?
Upvotes: 1
Views: 922
Reputation: 356
If using Jackson, you could achieve that with @JsonTypeInfo/@JsonSubTypes on the parent class, but a cast would still be needed to reach phoneNumber.
To avoid any class cast, you'll need to overload your controller method with as many signatures as needed (one per child class of PaymentTransactionDTO at least), and with an explicit JSON structure requirement
// should handle requests containing a phoneNumber attribute
@RequestMapping(method = RequestMethod.GET, params = {"phoneNumber"})
public ResponseEntity<TransactionStatus> payment(@PathVariable String accountNumber,
@Valid @RequestBody PhoneBillPaymentTransactionDTO phoneBillPaymentTransactionDTO) {
// code handling specially phone
}
// should handle any request not containing other specified attributes
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<TransactionStatus> payment(@PathVariable String accountNumber,
@Valid @RequestBody PaymentTransactionDTO paymentTransactionDTO) {
// code handling the generic transaction
}
Under you can still, from the 'phone' related code, call the base transaction controller method, or also split your controller/service into specific code relying on base implementation.
Upvotes: 1