@PathVariable和@RequestBody/@RequestParam结合使用

当总的业务逻辑类型相同,具体业务逻辑不同时(譬如乘车:高铁,汽车,自驾),使用注解@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);

}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值