Spring Boot集成OpenAPI3:多路由函数Path参数配置疑问
在多路由函数场景下配置OpenAPI3 Path参数
针对Spring Boot函数式端点多路由配置中无法直接通过@RouterOperation的params指定Path参数类型的问题,有两种实用解决方式:
1. 为单个@RouterOperation配置完整的@Operation属性
直接在带Path参数的@RouterOperation中,通过operation字段绑定@Operation注解,像单路由场景一样配置parameters,明确参数的位置、类型、描述等信息。
修改后的多路由配置示例:
@RouterOperations({ @RouterOperation(path = "/getAllPersons", beanClass = PersonService.class, beanMethod = "getAll"), @RouterOperation( path = "/getPerson/{id}", beanClass = PersonService.class, beanMethod = "getById", operation = @Operation( operationId = "getPersonById", summary = "根据ID获取Person", parameters = { @Parameter( in = ParameterIn.PATH, name = "id", description = "Person的唯一标识", required = true, schema = @Schema(type = "string") // 指定参数类型 ) }, responses = { @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Person.class))), @ApiResponse(responseCode = "404", description = "未找到对应Person") } ) ), @RouterOperation(path = "/createPerson", beanClass = PersonService.class, beanMethod = "save"), @RouterOperation( path = "/deletePerson/{id}", beanClass = PersonService.class, beanMethod = "delete", operation = @Operation( operationId = "deletePersonById", summary = "根据ID删除Person", parameters = { @Parameter( in = ParameterIn.PATH, name = "id", description = "Person的唯一标识", required = true, schema = @Schema(type = "string") ) }, responses = { @ApiResponse(responseCode = "204", description = "删除成功"), @ApiResponse(responseCode = "404", description = "未找到对应Person") } ) ) }) @Bean public RouterFunction<ServerResponse> personRoute(PersonHandler handler) { return RouterFunctions .route(GET("/getAllPersons").and(accept(MediaType.APPLICATION_JSON)), handler::findAll) .andRoute(GET("/getPerson/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById) .andRoute(POST("/createPerson").and(accept(MediaType.APPLICATION_JSON)), handler::save) .andRoute(DELETE("/deletePerson/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete); }
2. 在业务方法参数上添加@Parameter注解
由于@RouterOperation指定了beanClass和beanMethod,springdoc会自动识别对应方法参数上的OpenAPI注解,生成参数元数据。这种方式无需修改路由配置,更贴合关注点分离的原则。
在PersonService的对应方法中添加注解:
public class PersonService { // 其他方法... public Mono<Person> getById( @Parameter( in = ParameterIn.PATH, name = "id", description = "Person的唯一标识", required = true, schema = @Schema(type = "string") ) String id ) { // 业务逻辑实现 } public Mono<Void> delete( @Parameter( in = ParameterIn.PATH, name = "id", description = "Person的唯一标识", required = true, schema = @Schema(type = "string") ) String id ) { // 业务逻辑实现 } }
内容的提问来源于stack exchange,提问作者user1578872
相关产品推荐
相关产品推荐

