一个接口多个实现类,如何动态调用
方法一:使用ApplicationContext(也可以借助配置文件)
1、一个支付接口
package com.niuniu.order.service.pay;public interface PayService {String pay();
}
2、两种支付方法实现类
package com.niuniu.order.service.pay.impl;import com.niuniu.order.service.pay.PayService;
import org.springframework.stereotype.Service;@Service
public class ZfbPayServiceImpl implements PayService {@Overridepublic String pay() {return "zfb";}
}
package com.niuniu.order.service.pay.impl;import com.niuniu.order.service.pay.PayService;
import org.springframework.stereotype.Service;@Service
public class WeiXinPayServiceImpl implements PayService {@Overridepublic String pay() {return "weixin";}
}
3、自定义MyServiceFactory类
package com.niuniu.order.service.pay;import com.niuniu.order.service.pay.impl.WeiXinPayServiceImpl;
import com.niuniu.order.service.pay.impl.ZfbPayServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;@Service
public class MyServiceFactory {@Autowiredprivate ApplicationContext applicationContext;public PayService getPayService(String beanName){switch (beanName){case ("zfbPayServiceImpl") :return applicationContext.getBean(ZfbPayServiceImpl.class);case ("weiXinPayServiceImpl") :return applicationContext.getBean(WeiXinPayServiceImpl.class);default:throw new IllegalArgumentException("Unknown service type!");}}
}
4、Controller调用
@Autowiredprivate MyServiceFactory myServiceFactory;@PostMapping("/pay")public Response pay(){
// String s = myServiceFactory.getPayService("zfbPayServiceImpl").pay();String s = myServiceFactory.getPayService("weiXinPayServiceImpl").pay();return Response.ok(s);}
postman测试
方法二:使用Map存储各实现类的实例(策略模式)
package com.niuniu.order.service.pay;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Map;@Service
public class MyServiceFactory2 {/*** key是bean名称*/private final Map<String, PayService> payServiceMap;@Autowiredpublic MyServiceFactory2(Map<String, PayService> payServiceMap) {this.payServiceMap = payServiceMap;}public PayService getPayService(String beanName){return payServiceMap.get(beanName);}
}
controller调用:
@Autowiredprivate MyServiceFactory2 myServiceFactory2;@PostMapping("/pay")public Response pay(){String s = myServiceFactory2.getPayService("zfbPayServiceImpl").pay();
// String s = myServiceFactory2.getPayService("weiXinPayServiceImpl").pay();return Response.ok(s);}