Search code examples
springspring-mvcswagger-uidocumentation-generationspringfox

Hide return value from a Spring MVC controller in SpringFox 2


I have an async Spring MVC controller that returns Future. SpringFox 2 renders it as this:

enter image description here

How do I remove it? Thank you in advance!


Solution

  • It does not work with types. So, let's suppose that this is the controller method:

    public CompletableFuture<ResponseEntity<ResponseDTO>> getDTO() {
        return CompletableFuture.completedFuture(ResponseEntity.ok(new ResponseDTO());
    }
    

    Adding just the configuration:

    .genericModelSubstitutes(ResponseEntity.class, CompletableFuture.class)
    .directModelSubstitute(CompletableFuture.class, java.lang.Void.class)
    

    it will not work. The method needs to be modified to:

    public CompletableFuture getDTO() {
        return CompletableFuture.completedFuture(ResponseEntity.ok(new ResponseDTO());
    }
    

    Then the CompletableFuture definition will disappear from OpenAPI specs.

    Found a better approach. I'm using springfox version 2.8.0. If you have a look at their docs (RTFM) you can have type classes resolved to POJO using a type adapter. An example for this configuration is like this:

    import com.fasterxml.classmate.TypeResolver;
    
    @Configuration
    @EnableSwagger2
    public class SpringFoxConfig {
    
        @Autowired
        private TypeResolver typeResolver;
    
        @Bean
        public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("base package"))
                .paths(PathSelectors.any())
                .build()
                .genericModelSubstitutes(ResponseEntity.class)
                .alternateTypeRules(
    
     newRule(typeResolver.resolve(CompletableFuture.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                .useDefaultResponseMessages(false)
                .pathMapping("/");
    }
    

    And the controller method can be defined with types:

    public CompletableFuture<ResponseEntity<ResponseDTO>> getDTO() {
        return CompletableFuture.completedFuture(ResponseEntity.ok(new ResponseDTO());
    }