代码如下:
@Component
public class PayFactory implements ApplicationContextAware {
private static Map<String, PaymentService> payBeanMap;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
Map<String, PaymentService> map = applicationContext.getBeansOfType(PaymentService.class);
payBeanMap = new HashMap<>();
map.forEach((key, value) -> payBeanMap.put(value.getCode(), value));
}
public static <T extends PaymentService> T getPayService(String code) {
return (T) payBeanMap.get(code);
}
}
接口:
public interface PaymentService {
String getCode();
Result pay(List<PayBase> obj) throws Exception;
}
在方法中的getCode方法中,写入的就是枚举值.比如;
@Override
public String getCode() {
return PayCodeEnum.***.getCode();
}
利用枚举的code作为map的key
使用的时候:
PayFactory.getPayService(PayCodeEnum.JOINPAY.getCode()).pay();
这样就可以根据你定义的枚举的code,指定了对应的实现进行执行.