Spring 5 MVC 中的 Router Function 使用

Spring 5 发行已经好几年了,里面提出了好几个新点子。其中一个就是 RouterFunction ,这是个什么东西呢?

Spring框架给我们提供了两种http端点暴露方式来隐藏servlet原理,一种就是这多年大家都在使用的基于注解的形式 @Controller 或 @RestController 以及其他的注解如 @RequestMapping 、 @GetMapping 等等。另外一种是基于路由配置 RouterFunction 和 HandlerFunction 的,称为“函数式WEB”。这篇文章我们就是来介绍后面这种函数式web的。

为什要说这个东西呢?老老实实用注解不好吗?一个原因是它既然存在,我们就该学习 :smiley: 。第二个原因是WebFlux推荐使用这个方式,而Spring在将来有可能推荐使用WebFlux而非MVC(Spring mvc可能会被废弃)。所以我们需要提早掌握。

wait...你不是来宣传WebFlux的吧?放心,这篇文章里再也不会出现WebFlux了

既然基于注解的MVC和函数式开发是等效的,那我们就先看下他们的对比。下面分别是用两种风格实现的代码:

@RestController
@RequestMapping("/model/building")
@Slf4j
public class ModelBuildingController {

    @Autowired
    private IModelBuildingService modelBuildingService;

    @GetMapping("/{entId}/stations")
    public PagedResult<StationVO> getStations(@PathVariable("entId") Long entId) {
        List<StationBO> stationBoList = modelBuildingService.getStations(entId);
        List<StationVO> stationVoList = TransformUtils.transformList(stationBoList, StationVO.class);
        return PagedResult.success(stationVoList);
    }
}

再看函数式风格

import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

@Configuration
public class ModelBuildingRouting {

    @Autowired
    private IModelBuildingService modelBuildingService;

    @Bean
    public RouterFunction<ServerResponse> getModelBuildingRouters() {
        return RouterFunctions.route(GET("/model/building/{entId}/stations"),
                request -> {
                    Long entId = Long.valueOf(request.pathVariable("entId"));
                    List<StationBO> stationBoList = modelBuildingService.getStations(entId);
                    return ServerResponse.ok().body(PagedResu
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值