当总的业务逻辑类型相同,具体业务逻辑不同时(譬如乘车:高铁,汽车,自驾),使用注解@PathVariable和@RequestBody/@RequestParam可创建统一入口,然后根据SpringContextUtils找到具体的实现类,既精简了Rest代码又利于代码扩展。
/**
* @description:
* @author: 码上得天下
* @create: 2019-10-22 10:42
**/
@RestController
public class TransportTest {
/***
* @Description:
* /transportation/highspeedrail
* /transportation/bus
* /transportation/car
*/
@RequestMapping(value ="/transportation/{choice}",method = RequestMethod.GET)
public Result transportation(@PathVariable("choice") String choice, @RequestBody Map map){
// 拿到具体交通方式的bean (可根据choice创建枚举,自定义bean)
TransportService transportService = (TransportService) SpringContextUtils.getBean(choice);
// 执行具体交通方式的具体流程
Map resultMap = (Map) transportService.transport(map);
return new Result("1","请求成功",resultMap);
}
}
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
/**
* 根据beanId获取Bean
* @param beanId
* @return Object
*/
public static Object getBean(String beanId){
try{
return applicationContext.getBean(beanId);
}catch(Exception be){
return null;
}
}
public static <T> T getBean(Class<T> clazz) {
try {
return applicationContext.getBean(clazz);
} catch (Exception e) {
return null;
}
}
}
public interface TransportService<T> {
public T transport(Map map);
}