Search code examples
springdocspringdoc-openapi-ui

Disable sorting fields value alphabetically


I am using Spring Boot (v2.1.3 RELEASE) and SpringDoc. I already went through https://springdoc.org/springdoc-properties.html and https://springdoc.org/, but it looks like SpringDoc is automatically sorting the parameters alphabetically. How can we prevent this?

@Operation(summary = "Find Students")
@Parameter(in=ParameterIn.QUERY, name="page", description="Results page you want to retrieve (0..N)", schema=@Schema(defaultValue = 0))
@Parameter(in=ParameterIn.QUERY, name="size", description="Number of records per page.", schema=@Schema(defaultValue =50))
@Parameter(in=ParameterIn.QUERY, name="search_type", description=AppConstants.SEARCH_TYPE, schema=@Schema(allowableValues= {"Starts", "Contains"},defaultValue = "Starts"))
@ApiCountryHeader
@GetMapping(value = "/students")
public ResponseEntity<List<Students>> findStudentss(
        @Parameter(description  = "") @RequestParam(required = false) String studentCd,
        @Parameter(description  = "") @RequestParam(required = false) String studentName,
        @Parameter(hidden=true) String search_type){

    ....
    ....
    ...
    return new ResponseEntity<>(studentts, HttpStatus.OK);
}

Solution

  • Fields are not sorted alphabetically, but the order of declaration is preserved.

    You can change the fields order, using the different available customizers:

    • OpenApiCustomiser: To customize the OpenAPI object
    • OperationCustomizer: To customize an operation based on the HandlerMethod

    For example:

    @RestController
    public class HelloController {
    
        @GetMapping(value = "/persons")
        public String getPerson(String b, String a) {
            return null;
        }
    
        @Bean
        OperationCustomizer operationCustomizer() {
            return (Operation operation, HandlerMethod handlerMethod) -> {
                if ("getPerson".equals(handlerMethod.getMethod().getName())) {
                    List<Parameter> parameterList = operation.getParameters();
                    if (!CollectionUtils.isEmpty(parameterList))
                        Collections.reverse(parameterList);
                }
                return operation;
            };
        }
    
    }