【发布时间】:2020-08-27 16:19:00
【问题描述】:
我有一个多态服务,像这样:
public abstract class PaymentService {
abstract boolean processPayment(Payment payment);
}
@Service
public class CreditPaymentService extends PaymentService {
@Override
public boolean processPayment(Payment payment) {
// method implementation
}
}
@Service
public class CashPaymentService extends PaymentService {
@Override
public boolean processPayment(Payment payment) {
// method implementation
}
}
在我的 PaymentController 中,我收到了一笔付款,我必须将它发送到正确的服务来处理它,具体取决于付款的类型。
@Controller
public class PaymentController {
@Autowired
private PaymentService service;
@Override
@PostMapping
public ResponseEntity<Payment> processPayment(@RequestBody Payment payment) {
service.processPayment(payment);
return noContent().build();
}
}
spring 如何知道要实例化哪个服务?
【问题讨论】:
-
@David Conrad 是对的。另外,仅仅注入子类有什么害处?
标签: java spring polymorphism autowired