简体   繁体   中英

Swagger UI with swagger.yaml in SpringBoot

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM