Spring boot 集成Swagger

Spring boot集成 Swagger找了很多资料,总结一下。

前提是spring boot项目

第一步导入jar包

 

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>


        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.13</version>
        </dependency>

  第二步 我们需要在代码中添加支持,于 Application 同级目录添加 Swagger 配置类.

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket config() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.pxx.xxx.controller"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Blog系统API文档")
                .contact(new Contact("作者", "访问地址", "联系方式"))
                .build();
    }
}

  

这时可以访问:

http://localhost:8082/v2/api-docs测试返回数据

 

第三步 使用Swagger-ui下载文件

 

从官方 GitHub https://github.com/swagger-api/swagger-ui 下载整个项目包 、 解压, 然后运行 dist 目录中的文件 拷贝到项目resources下的public文件下,并且修改index.html

  const ui = SwaggerUIBundle({
//http://localhost:8082/ 是项目的访问路径,注意更换
    url: "http://localhost:8082/v2/api-docs",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

  

posted on 2017-11-01 15:09  Snowman-Nunu  阅读(145)  评论(0编辑  收藏  举报

导航