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(PagedResult.success(stationVoList));