5分钟学会swagger配置

swagger概述

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。 总体目标是使客户端和文件系统作为服务器以同样的速度来更新。 文件的方法/参数/模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

一、添加maven依赖


    <!--配置swagger-->
    <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger2</artifactId>
       <version>2.6.1</version>
    </dependency>
    <dependency>
       <groupId>io.springfox</groupId>
       <artifactId>springfox-swagger-ui</artifactId>
       <version>2.6.1</version>
    </dependency>
 
 
 
 

二、添加swagger配置类

    /**
     * Swagger配置类.
     */

    @EnableSwagger2                // Swagger的开关,表示已经启用Swagger
    @Configuration                 // 声明当前配置类
    public class SwaggerConfiguration {

       @Value("${swagger.basePackage}")    
       private String basePackage;       // controller接口所在的包

       @Value("${swagger.title}")    
       private String title;           // 当前文档的标题

       @Value("${swagger.description}")
       private String description;         // 当前文档的详细描述

       @Value("${swagger.version}")
       private String version;         // 当前文档的版本

       @Bean
       public Docket createRestApi() {
          return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
       }

       private ApiInfo apiInfo() {
          return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(version)
                .build();
       }

    }



 
 

三、application.yml添加配置

    # 配置swagger
        swagger:
            basePackage: com.yuan.controller
            title: 猿医生のAPI
            description: 一生猿,一世猿。
            version: V1.0
 
 
 
 


四、添加接口

    /**
     * Created by 猿医生 on 2018/6/21.
     */
    @Api(value = "yuan")
    @RestController
    public class TestController{

        @ApiOperation(value="yisheng")
        @GetMapping("/hello")
        public String hello() {
            return "I Love You。";
        }
    
    }


 
 

五、测试

    访问地址:http://localhost:端口号/项目名称/swagger-ui.html     

    当然,也有很多spring boot的项目是没有项目名称的,http://localhost:端口号/swagger-ui.html

    本项目的地址是 http://localhost:8080/swagger-ui.html

     

       响应内容 

六、beautiful UI

    <dependency>
       <groupId>com.github.xiaoymin</groupId>
       <artifactId>swagger-bootstrap-ui</artifactId>
       <version>1.6</version>
    </dependency>
 
  
 

本项目的地址是 http://localhost:8080/doc.html







小结

谢谢观赏,我叫猿医生

猿友推荐:正在奔跑的程序猿

猜你喜欢

转载自blog.csdn.net/qq_42175986/article/details/80760038