基于 @Resource 的支付 Service 多实现类完整示例

张开发
2026/4/10 3:35:31 15 分钟阅读

分享文章

基于 @Resource 的支付 Service 多实现类完整示例
1DTOPayCreateDTO.javaimport lombok.Data; Data public class PayCreateDTO { private String orderNo; // 订单号 private Integer amount; // 支付金额 }2Controller里面直接写 Resource不单独抽出来import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; RestController RequestMapping(/pay) public class PayController { // 直接写在真实代码里 Resource(name alipayService) private PayService alipayService; Resource(name wxpayService) private PayService wxpayService; // // 支付宝支付 PostMapping(/alipay) public Result aliPay(RequestBody PayCreateDTO dto) { return alipayService.pay(dto); } // 微信支付 PostMapping(/wxpay) public Result wxPay(RequestBody PayCreateDTO dto) { return wxpayService.pay(dto); } }3Service 接口PayService.javapublic interface PayService { Result pay(PayCreateDTO dto); }4实现类 1支付宝AlipayServiceImpl.javaimport org.springframework.stereotype.Service; Service(alipayService) // 这里的名字和 Resource 对应 public class AlipayServiceImpl implements PayService { Override public Result pay(PayCreateDTO dto) { String result 支付宝支付成功 → 订单 dto.getOrderNo() 金额 dto.getAmount(); return Result.ok(result); } }5实现类 2微信WxpayServiceImpl.javaimport org.springframework.stereotype.Service; Service(wxpayService) // 这里的名字和 Resource 对应 public class WxpayServiceImpl implements PayService { Override public Result pay(PayCreateDTO dto) { String result 微信支付成功 → 订单 dto.getOrderNo() 金额 dto.getAmount(); return Result.ok(result); } }一个类只能做一件事service/ impl/ AlipayServiceImpl.java → 支付宝单独一个类 WxpayServiceImpl.java → 微信单独一个类6拷贝工具类BeanCopyUtils.javaimport org.springframework.beans.BeanUtils; public class BeanCopyUtils { public static T T copy(Object source, ClassT clazz) { if (source null) return null; T target BeanUtils.instantiateClass(clazz); BeanUtils.copyProperties(source, target); return target; } }

更多文章