摘要:public interface PaymentService { void pay(double amount);}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Qualifierp
还在用冗长的if-else或switch语句管理多个服务实现?
相信不少Spring Boot开发者都遇到过这样的场景:需要根据不同条件动态选择不同的服务实现。
如果告诉你可以完全摆脱条件判断,让Spring自动选择合适的实现——只需要一个注解,你是否感兴趣?
本文将详细介绍这种优雅的实现方式。
if (paymentType.equals("Paypal")) { return new PaypalPaymentService;} else if (paymentType.equals("Stripe")) { return new StripePaymentService;}❌ 这种写法存在明显问题:代码冗余、难以维护、扩展性差。
接下来看看如何优化。
最近我们翻译了Spring Boot和Spring AI的中文文档:
Spring Boot 3.4:https://doc.spring4all.com/spring-boot/3.4.6/
Spring Boot 3.5:https://doc.spring4all.com/spring-boot/3.5.0/
Spring AI 1.0.0:https://doc.spring4all.com/spring-ai/reference/
public interface PaymentService { void pay(double amount);}@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Qualifierpublic @interface PaymentType { String value;}@PaymentType("PAYPAL")@Servicepublic class PaypalPaymentService implements PaymentService { public void pay(double amount) { System.out.println("使用PayPal支付:$" + amount); }}@PaymentType("Stripe")@Servicepublic class StripePaymentService implements PaymentService { public void pay(double amount) { System.out.println("使用Stripe支付:$" + amount); }}@Componentpublic class PaymentServiceFactory { private final Map serviceMap = new HashMap; @Autowired public PaymentServiceFactory(List services) { for (PaymentService service : services) { PaymentType Annotation = service.getClass.getAnnotation(PaymentType.class); if (annotation != null) { serviceMap.put(annotation.value, service); } } } public PaymentService getService(String type) { return serviceMap.get(type); }}@RestControllerpublic class PaymentController { private final PaymentServiceFactory paymentServiceFactory; @Autowired public PaymentController(PaymentServiceFactory paymentServiceFactory) { this.paymentServiceFactory = paymentServiceFactory; } @PostMapping("/pay") public String makePayment(@RequestParam String method, @RequestParam double amount) { PaymentService service = paymentServiceFactory.getService(method.toUpperCase); if (service == null) { return "暂不支持该支付方式"; } service.pay(amount); return "支付成功"; }}将@PaymentType与@Profile("prod")结合使用,Spring会根据当前激活的配置文件自动选择对应的实现。
来源:码农看看
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!