7
votes

We have a SpringBoot (version 1.5.12) REST Api with springfox-swagger2 and springfox-swagger-ui (version 2.9.2)

@EnableSwagger2
public class Application extends SpringBootServletInitializer {
   @Bean
   public Docket swagger() {
       return new Docket(SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }

I can see the Swagger UI at http://localhost:8080/swagger-ui.html

How can I configure swagger-ui to read my swagger.yaml/json configuration file instead to generate it automatically? I tried several configuration without success.

1

1 Answers

15
votes

You need to create a class which can provide a SwaggerResourcesProvider @Primary bean, which specifies the location of the config as below (considering the swagger.json file is present in src/main/resources)

@Configuration
public class SwaggerSpecConfig {

    @Primary
    @Bean
    public SwaggerResourcesProvider swaggerResourcesProvider(InMemorySwaggerResourcesProvider defaultResourcesProvider) {
        return () -> {
            SwaggerResource wsResource = new SwaggerResource();
            wsResource.setName("new spec");
            wsResource.setSwaggerVersion("2.0");
            wsResource.setLocation("/swagger.json");

            List<SwaggerResource> resources = new ArrayList<>(defaultResourcesProvider.get());
            resources.add(wsResource);
            return resources;
        };
    }
}

Then on the Swagger UI, you'll be able to select the spec from your json (named as new spec here) as below:

enter image description here

Here's a link to the Springfox documentation: http://springfox.github.io/springfox/docs/current/#aggregating-multiple-swagger-specifications-in-the-same-swagger-ui