在实际的业务,开发中经常会出现在多个业务完成了同一个业务后需要回调到各自业务中来完成不同的操作,例如订单平台,在调佣统一的支付接口完成支付后,订单支付系统会将支付结果回调,这时,我们可能需要根据业务类型来回调到具体的service中
1:添加一个SpringBeanUtil的组件类,添加@Component注解,继承ApplicationContextAware
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean(String className) throws BeansException,IllegalArgumentException {
if(className==null || className.length()<=0) {
throw new IllegalArgumentException("className为空");
}
return applicationContext.getBean(className);
}
}
2.定义一个基础接口类
public interface BaseService {
BaseRestResponse<Map<String,Object>> saveService(Map<String,Object> param);
}
3:定义一个factory类
通过业务标识supplier 来反射找到对应的service,注意,具体的业务实现类要和supplier+"Service" 一致
例如:supplier 为Test,实现类名称应该为TestService
public static BaseService getService(String supplier) {
try {
//String serviceStr = supplier.substring(0, 1).toUpperCase()+supplier.substring(1);
return (BaseService) SpringBeanUtil.getBean(supplier+"Service");
} catch (Exception e) {
e.printStackTrace();
//throw new IllegalArgumentException("无法识别的类型");
return null;
}
}
4:定义TestService
业务实现类需要implements BaseService ,具体的业务实现逻辑就在saveService方法中开发编码