swagger工具简介

Swagger是全球最大的OpenAPI规范(OAS)API开发工具框架,支持从设计和文档到测试和部署的整个API生命周期的开发。简单点说,就是按照swagger的规范书写接口,swagger会自动帮你生成接口文档、以及接口的测试

将swagger整合到spring boot项目中

  1、配置依赖的包

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>

  2、swagger配置文件

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     * @return
     */
    @Bean
    public Docket createRestfulApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
               // .apis(RequestHandlerSelectors.basePackage("com.lance.learn.springbootswagger.controller"))  //暴露接口地址的包路径
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                //页面标题
                .title("Spring Boot 测试使用 Swagger2 构建RESTful API")
                //创建人
                .contact(new Contact("test", "https://www.cnblogs.com", "123@qq.com"))
                //版本号
                .version("2.0")
                //描述
                .description("API 描述")
                .build();
    }

}

3、对于接口的配置--基于注解

  @Api()用于类:表示标识这个类是swagger的资源 不标识也无所谓

@Api(value="用户controller",tags={"用户操作接口"})

  @ApiOperation()用于方法; 表示一个http请求的操作  不标识也无所谓

   @ApiOperation(value="根据用户编号获取用户姓名", notes="test: 仅1和2有正确返回")

  @ApiImplicitParam() 用于方法 表示单独的请求参数 

@ApiImplicitParam(paramType="query", name = "userNumber", value = "用户编号", required = true, dataType = "Integer")

  @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")
    })

 4、效果展示

   

  

原文地址:https://www.cnblogs.com/ysmdbk/p/11540541.html