猿问

如何在 spring 控制器中使用枚举作为参数,该控制器使用“spring”

假设我有一个用枚举模式定义的参数:


paths:

  /echo:

    get:

      parameters:

      - name: someEnum

        in: query

        required: true

        schema:

          type: string

          enum: [A, B, C]

      responses:

        200:

          description: Success

          content:

            text/plain:

              schema:

                type: string

Swagger codegen 为语言生成以下 Java 接口spring:


    @ApiOperation(value = "", nickname = "echoGet", notes = "", response = String.class, tags={  })

    @ApiResponses(value = { 

        @ApiResponse(code = 200, message = "Success", response = String.class) })

    @RequestMapping(value = "/echo",

        produces = { "text/plain" }, 

        method = RequestMethod.GET)

    default ResponseEntity<String> echoGet(@NotNull @ApiParam(value = "", required = true, allowableValues = "A, B, C") @Valid @RequestParam(value = "someEnum", required = true) String someEnum) {

        if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {

        } else {

            log.warn("ObjectMapper or HttpServletRequest not configured in default EchoApi interface so no example is generated");

        }

        return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);

    }

someEnum生成接口的类型是字符串。如何用具有“A”、“B”、“C”值的 Java 枚举替换它?


长风秋雁
浏览 149回答 2
2回答

绝地无双

将命名类型添加到模式并使用它:paths:&nbsp; /echo:&nbsp; &nbsp; get:&nbsp; &nbsp; &nbsp; parameters:&nbsp; &nbsp; &nbsp; &nbsp; - name: someEnum&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in: query&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; required: true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; schema:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $ref: '#/components/schemas/MyEnum'&nbsp; &nbsp; &nbsp; responses:&nbsp; &nbsp; &nbsp; &nbsp; 200:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; description: Success&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; content:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; text/plain:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; schema:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: stringcomponents:&nbsp; schemas:&nbsp; &nbsp; MyEnum:&nbsp; &nbsp; &nbsp; type: string&nbsp; &nbsp; &nbsp; enum: [A,B,C]

LEATH

在部分中定义您的枚举架构components/schemas,并$ref从参数定义中定义它,如下所示。在这种情况下,Swagger Codegen 会将枚举生成为实际的 Java 枚举。openapi: 3.0.0...paths:&nbsp; /echo:&nbsp; &nbsp; get:&nbsp; &nbsp; &nbsp; parameters:&nbsp; &nbsp; &nbsp; - name: someEnum&nbsp; &nbsp; &nbsp; &nbsp; in: query&nbsp; &nbsp; &nbsp; &nbsp; required: true&nbsp; &nbsp; &nbsp; &nbsp; schema:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $ref: '#/components/schemas/MyEnum'&nbsp; &nbsp; &nbsp; ...components:&nbsp; schemas:&nbsp; &nbsp; MyEnum:&nbsp; &nbsp; &nbsp; type: string&nbsp; &nbsp; &nbsp; enum: [A, B, C]
随时随地看视频慕课网APP

相关分类

Java
我要回答