1)DTO(PayCreateDTO.java)
import lombok.Data;
@Data
public class PayCreateDTO {
private String orderNo; // 订单号
private Integer amount; // 支付金额
}
2)Controller(里面直接写 @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);
}
}
3)Service 接口(PayService.java)
public interface PayService {
Result pay(PayCreateDTO dto);
}
4)实现类 1:支付宝(AlipayServiceImpl.java)
import 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.java)
import 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.java)
import org.springframework.beans.BeanUtils;
public class BeanCopyUtils {
public static <T> T copy(Object source, Class<T> clazz) {
if (source == null) return null;
T target = BeanUtils.instantiateClass(clazz);
BeanUtils.copyProperties(source, target);
return target;
}
}