简体   繁体   English

如何在单个 controller / 服务方法中处理多个继承的 DTO?

[英]How to handle Multiple inherited DTOs in a single controller / service method?

I have got PaymentTransactionDTO as superclass and subclasses like PhoneBillPaymentTransactionDTO which has a field as phoneNumber etc.我有 PaymentTransactionDTO 作为超类和子类,例如 PhoneBillPaymentTransactionDTO,其中有一个字段为 phoneNumber 等。

and I would like to handle these DTOs from single payment service.我想通过单一支付服务处理这些 DTO。 My controller method like below;我的 controller 方法如下;

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.当我将 PhoneBillPaymentTransactionDTO 发布到上述方法时,我无法到达 phoneNumber 字段,因为我在方法签名中有 PaymentTransactionDTO。

How should I have a design to manage multiple inherited dtos from single method?我应该如何设计从单一方法管理多个继承的 dto?

If using Jackson , you could achieve that with @JsonTypeInfo/@JsonSubTypes on the parent class, but a cast would still be needed to reach phoneNumber.如果使用 Jackson ,您可以使用父 class 上的@JsonTypeInfo/@JsonSubTypes来实现,但仍需要强制转换才能到达 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 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.在您仍然可以从“电话”相关代码中调用基本事务 controller 方法,或者也可以根据基本实现将您的控制器/服务拆分为特定代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM