if else太多怎么代替,太难维护?可以使用spring-plugin 插件系统

2021-05-07 01:27

阅读:535

标签:blog   开启   ram   color   EAP   equal   static   void   gis   

一、springboot +spring-plugin

二、针对根据入参不同可能有不同实现逻辑的场景写个demo,如:针对支付宝或者微信支付渠道发起的支付请求

1).引入相关依赖

        org.springframework.plugin
            spring-plugin-core
        

 

2).请求参数实体属性

@Data
public class PayRequestVO {

    private String channel;
    
    private String phone;
    
    private BigDecimal money;
}

 

支付接口:

public interface OrderPayOperationService extends Plugin {

    public String orderPay(PayRequestVO vo);
}

支付宝支付实现:

@Service
public class AlipayOrderPayOperationServiceImpl implements OrderPayOperationService {

    @Override
    public boolean supports(PayRequestVO delimiter) {
        return "alipay".equalsIgnoreCase(delimiter.getChannel());
    }

    @Override
    public String orderPay(PayRequestVO vo) {
        return "支付宝支付";
    }

}

微信支付实现:

@Service
public class WxOrderPayOperationServiceImpl implements OrderPayOperationService {

    @Override
    public boolean supports(PayRequestVO delimiter) {
        return false;
    }

    @Override
    public String orderPay(PayRequestVO vo) {
        return "微信支付";
    }

}

将业务接口注入到插件系统:@EnablePluginRegistries({ OrderPayOperationService.class })

test:

@SpringBootApplication //Spring Boot核心注解,用于开启自动配置
@EnablePluginRegistries({ OrderPayOperationService.class })
@Slf4j
public class DemoApplication {
    //程序可以直接在此启动

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

        PluginRegistry orderPayOperationServicePluginRegistry = (PluginRegistry) context
                .getBean("orderPayOperationServiceRegistry");
        PayRequestVO vo = new PayRequestVO();
        vo.setChannel("alipay");
        vo.setPhone("1231231231");
        vo.setMoney(new BigDecimal(100));
        //获取插件
        OrderPayOperationService orderPayOperationService = orderPayOperationServicePluginRegistry.getPluginFor(vo);//getPlugins();
        //发起订单支付
        String orderPay = orderPayOperationService.orderPay(vo);
        log.info("支付返回:{}", orderPay);
    }

}

运行结果:

技术图片

 

 总结:

1.使用spring-plugin可以方便代码拓展功能,方便维护;

2.架构清晰,结构分层;

3.业务实现解耦,保持原有业务稳定性,新增业务无需动到框架层面.

参考:https://blog.csdn.net/u010192145/article/details/90487058

 

if else太多怎么代替,太难维护?可以使用spring-plugin 插件系统

标签:blog   开启   ram   color   EAP   equal   static   void   gis   

原文地址:https://www.cnblogs.com/zyf-yxm/p/13186968.html


评论


亲,登录后才可以留言!