stn精炼_精炼功能性弹簧

stn精炼

上周,我写了一篇关于如何通过功能性方法向配置迁移现有Spring Boot应用程序的文章 。 从那时起,我在基辅的Rockstar Night上就该主题进行了演讲,并得到了有趣的反馈。

处理程序类是必需的

处理程序功能无法移至程序包。

它们需要符合ServerRequest → Mono签名。

classPersonHandler(privatevalpersonRepository:PersonRepository){
  funreadAll(request:ServerRequest)=
      ServerResponse.ok().body(personRepository.findAll())
  funreadOne(request:ServerRequest)=
      ServerResponse.ok().body(
           personRepository.findById(request.pathVariable("id").toLong()))
}

如果需要依赖项-就是这种情况,则需要在更大范围内提供它们。 类使此类作用域易于使用。

不需要绕行包装类

可以这样写路由:

classPersonRoutes(privatevalhandler:PersonHandler){
  funroutes()=router{
    "/person".nest{
      GET("/{id}",handler::readOne)
      GET("/",handler::readAll)
    }
  }
}

这是可以相应地配置它们的方式:

beans{
  bean{
    PersonRoutes(PersonHandler(ref())).routes()
  }
}

因为可以使用handler依赖项直接注入路由,所以不需要包装类。 上面的代码可以重写为:

funroutes(handler:PersonHandler)=router{
  "/person".nest{
    GET("/{id}",handler::readOne)
    GET("/",handler::readAll)
  }
}

beans{
  bean{
    routes(PersonHandler(ref()))
  }
}

保持课堂状态只是功能前世界的一种古老反映。

整理路线

该演示项目仅配置2条路由,但在实际项目中,它们必然会更多。 在某些时候这将变得难以管理。

在注释世界中,路径被组织成控制器类。 无类路由功能的组织模式是什么?

可以使用andOther()函数轻松地构成路线。 它的定义如下:

org / springframework / web / reactive / function / server / RouterFunction.java
interfaceRouterFunction{

  defaultRouterFunctionandOther(RouterFunctionother){
    returnnewRouterFunctions.DifferentComposedRouterFunction(this,other);
  }

  ...
}

让我们定义不同的路由功能:

funrouteId(handler:PersonHandler)=router{
    GET("/person/{id}",handler::readOne)
}

funrouteAll(handler:PersonHandler)=router{
    GET("/person",handler::readAll)
}

现在,编写它们非常简单:

bean{
  valhandler=PersonHandler(ref())
  routeId(handler).andOther(routeAll(handler))
}

或使用stdlib

bean{
  with(PersonHandler(ref())){
    routeId(this).andOther(routeAll(this))
  }
}
这篇文章的完整源代码可以在Github上找到。

翻译自: https://blog.frankel.ch/refining-functional-spring/

stn精炼

你可能感兴趣的:(stn精炼_精炼功能性弹簧)