if else太多怎么代替,太難維護?可以使用spring-plugin 插件系統


一、springboot +spring-plugin

二、針對根據入參不同可能有不同實現邏輯的場景寫個demo,如:針對支付寶或者微信支付渠道發起的支付請求

1).引入相關依賴

        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
        </dependency>

 

2).請求參數實體屬性

@Data
public class PayRequestVO {

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

 

支付接口:

public interface OrderPayOperationService extends Plugin<PayRequestVO> {

    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<OrderPayOperationService, PayRequestVO> orderPayOperationServicePluginRegistry = (PluginRegistry<OrderPayOperationService, PayRequestVO>) 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM