使用场景
实际项目上中遇到交易使用多种支付方式,如微信原生支付,微信小程序支付,微信公众号支付,支付宝之支付等等等。简化多个if判断,switch case 使用。
使用介绍
1、首先说一下spring Autowired 注解除了我们正常使用的之外还有一点:
@Autowired标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类 型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。非常牛X的操作。
需要注意的是:应用于map的时候key必须为String类型(实现类的名字)
看下源码
好啦 直接上代码:
cotroller注入
public class x{
@Autowired
private Map<String, PayStrategy> payStategies;
@RequestMapping(value = "/pay",method = RequestMethod.GET)
public Object pay(int storeType, String version, int channel,.....) {
PayStrategy payStrategy = null;
PayChannelStrategyEnum payChannelStrategyEnum = PayChannelStrategyEnum.getPayChannelStrategyEnum(channel);
if (payChannelStrategyEnum == null) {
outMap.put("code", "fail");
outMap.put("messge", "支付通道异常");
return outMap;
}
for (Map.Entry<String, PayStrategy> entry : payStategies.entrySet()) {
if (payChannelStrategyEnum.getPayStrategy().equals(entry.getValue().getClass().getSimpleName())) {
payStrategy = entry.getValue();
}
}
if (payStrategy != null) {
Map<String, Object> params = new ConcurrentHashMap<String, Object>();
params.put("storeType",storeType);
params.put("version",version);
。。。。。。
Map map = payStrategy.doPay(params);
return map;
}
}
}
支付策略接口:
public interface PayStrategy {
public Map doPay(Map<String, Object> map);
}
//支付宝支付
@Service("aliPayNewStrategy")
public class AliPayStrategy implements PayStrategy {
@Override
public Map doPay(Map<String, Object> map) {
System.out.println("支付宝支付");
return null;
}
}
//微信原生支付
@Service("wechatStrategy")
public class WechatStrategy implements PayStrategy {
@Override
public Map doPay(Map<String, Object> map) {
System.out.println("微信原生支付");
return null;
}
}
定义枚举类
public enum PayChannelStrategyEnum {
ALI_PAY_CHANNEL(1, WechatStrategy .class.getSimpleName()),
WECHAT_PAY_CHANNEL(0, AliPayStrategy .class.getSimpleName());
private int channelCode;
private String payStrategy;
public int getChannelCode() {
return channelCode;
}
public String getPayStrategy() {
return payStrategy;
}
public void setPayStrategy(String payStrategy) {
this.payStrategy = payStrategy;
}
public void setChannelCode(int channelCode) {
this.channelCode = channelCode;
}
private PayChannelStrategyEnum(int channelCode, String payStrategy) {
this.channelCode = channelCode;
this.payStrategy = payStrategy;
}
public static PayChannelStrategyEnum getPayChannelStrategyEnum(int code) {
PayChannelStrategyEnum[] payChannelStrategyEnums = PayChannelStrategyEnum.values();
PayChannelStrategyEnum result = null;
for (PayChannelStrategyEnum payChannelStrategyEnum : payChannelStrategyEnums) {
if (payChannelStrategyEnum.getChannelCode() == code) {
result = payChannelStrategyEnum;
break;
}
}
return result;
}
}