@Autowired搭配@interface注解实现策略模式

应用场景:存在银行卡和社保卡的支付、退货等接口,接口报文中使用transWay表示银行卡(0)和社保卡(1),transType表示支付(1)、退货(2)。那么由其组合便能出现四个逻辑,所以要实现动态的逻辑分发。

domain

@Data
public class PosApiReq {
    /** 交易方式 **/
    private String transWay;
    /** 交易类型 **/
    private String transType;
}

service

  • 接口定义
public interface ICommonService {

    public Object handler(String json);
}
  • 银行卡消费
@Service
@CodeType("01")
public class BankConsumService implements ICommonService{

    @Override
    public Object handler(String json) {
        System.out.println("银行卡消费开始:" + json);
        return "bank-consum";
    }
}
  • 银行卡退货
@Service
@CodeType("02")
public class BankRefundService implements ICommonService{

    @Override
    public Object handler(String json) {
        System.out.println("银行卡退货开始:" + json);
        return "bank-refund";
    }
}
  • 社保卡消费
@Service
@CodeType("11")
public class SocConsumService implements ICommonService{

    @Override
    public Object handler(String json) {
        System.out.println("社保卡消费开始:" + json);
        return "soc-consum";
    }
}
  • 社保卡退货
@Service
@CodeType("12")
public class SocRefundService implements ICommonService{

    @Override
    public Object handler(String json) {
        System.out.println("社保卡退货开始:" + json);
        return "soc-refund";
    }
}

controller

@RestController
public class ServerController {

    private final Map<String, ICommonService> handlerMap = new HashMap<>();

    @Autowired
    private void setHandler(List<ICommonService> commonServiceList) {
        for (ICommonService commonService : commonServiceList) {
            handlerMap.put(commonService.getClass().getAnnotation(CodeType.class).value(), commonService);
        }
    }


    @Anonymous
    @RequestMapping("/api")
    public Object api(@RequestBody PosApiReq posApiReq) {
        
        String transWay = posApiReq.getTransWay();
        String transType = posApiReq.getTransType();

        // 01 银行卡消费、02银行卡退货、11 社保卡消费、 12社保卡退货
        String value = transWay+transType;

        ICommonService commonService = handlerMap.get(value);

        Object object = commonService.handler(posApiReq.toString());
       
        return object;
    }
}

annotation

@Target(value={ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CodeType {
    String value();
}

此方式完美的解决了根据不通交易调用不通逻辑的问题,如果新添加一类交易,只需要扩展实现ICommonService 接口的新类就可以。

你可能感兴趣的:(Spring,Boot,JAVA,策略模式,开发语言)