一、想要达到的目的
一个主Controller类根据交易码字段来访问不同的业务实现ServiceImpl
二、代码实现
java代码实现
/**
* 入口controller类
*/
@Slf4j
@RestController
public class CoreController {
@AcpsApi
@PostMapping("/acps")
public ResponseMsg acpsGate(@Valid @RequestBody RequestMsg requestMsg) throws Exception {
ResponseMsg response = BusinessFactory.getService(requestMsg.getHeader().getTrans_code()).doExecute(requestMsg);
return response;
}
}
/**
* BusinessFactory类
*/
public class BusinessFactory {
private static final Map<String, IBusinessService> SERVICE_MAP = Maps.newHashMap();
private BusinessFactory() {
}
public static IBusinessService getService(String commandCode) {
IBusinessService businessService = SERVICE_MAP.get(commandCode);
if (null == businessService) {
throw new AcpsBusinessException(ServiceErrorCode.TRANS_CODE_ERROR);
}
return businessService;
}
/**
* 注册业务实现类
*
* @param code
* @param businessService
*/
public static void registerService(String code, IBusinessService businessService) {
SERVICE_MAP.put(code, businessService);
}
}
/**
* 主业务接口
*/
public interface IBusinessService {
/**
* 业务执行方法
*
* @return
*/
ResponseMsg doExecute(RequestMsg requestMsg) throws Exception;
}
/**
* 主业务抽象类
*/
@Slf4j
public abstract class AbstractBusinessServiceImpl implements IBusinessService, InitializingBean {
private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
/**
* 获取指令代码
*
* @return
*/
protected abstract String getCommandCode();
/**
* 执行方法
* @return
*/
@Override
public ResponseMsg doExecute(RequestMsg requestMsg) throws Exception {
throw new AcpsBusinessException(ServiceErrorCode.RESPONSE_CODE_ILLEGAL_DATA);
}
protected void validateParam(Object object) {
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();
if (iterator.hasNext()) {
throw new AcpsBusinessException(ServiceErrorCode.REQUEST_PARAM_ILLEGAL_DATA.getCode(), iterator.next().getMessage());
}
}
protected <T> RequestMsg<T> validBody(RequestMsg requestMsg, Class<T> aClass){
RequestMsg<T> req = JSONUtils.parseGenerics(JSONUtils.toJSONString(requestMsg), RequestMsg.class, aClass);
validateParam(req.getBody());
return req;
}
}
/**
* 具体业务实现类
*/
@Slf4j
@Service
public class BizCommandConsumeServiceImpl extends AbstractBusinessServiceImpl implements InitializingBean {
@Override
public ResponseMsg doExecute(RequestMsg requestMsg) throws Exception {
//业务实现代码
return ResponseMsg;
}
@Override
public void afterPropertiesSet() throws Exception {
BusinessFactory.registerService(getCommandCode(), this);
}
@Override
protected String getCommandCode() {
return TransCode.J00002.getCode();
}
}