Spring Boot --- Swagger


关于Swagger

Swagger文档–Springfox references Documentation

Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:

  • Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
  • Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
  • Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
  • Swagger 有一个强大的社区,里面有许多强悍的贡献者。

Spring Boot 集成Swagger

依赖

<!-- swagger库 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- swagger页面 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>

配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot整合Swagger测试项目")
                .description("测试测试")
                .contact("yucoang")
                .version("1.0")
                .build();
    }
}

访问Swagger

http://localhost:8080/swagger-ui

Swagger注解

@Api

在Swagger中,默认以一个Controller类为一个分组,并以Controller类名作为组名与描述
可在Controller中使用@Api设置信息说明.

@Api("Hello模块")
@RestController
@RequestMapping("/hello")
public class HelloContrller {
    ...
}

@ApiOperation

在Swagger中,默认以方法名作为API名称.可在方法上使用@ApiOperation设置信息说明

@ApiOperation(value = "say hello", notes="return Hello World")
@GetMapping("/say")
public String sayHello(){
    return "Hello World";
}

@ApiImplicitParams@ApiImplicitParam

属性 可选值 说明
name 参数名,例:@requestParams("a") String b,则name=a
value 参数说明
dataType 原始数据类型(string,int,long等)或class名 参数类型
paramType query,path,body,header,form 参数方式
required true,false 是否必填
allowMultiple true,false 允许多个值
defaultValue 默认值
allowableValues 允许的值
access
  • name : 参数名
    必须与实际参数传入变量名一致.,显示在Parameters表格的Parameter列

  • value : 参数说明
    可任意填写,显示在Parameters表格的Description列

  • paramType 参数方式
    根据参数的传入方式

对应参数传入方式
query @RequestParam,@ModelAttribute
path @PathVariable
body @RequestBody
header @RequestHeader

- dataType:参数类型
可以是简单数据类型,如string,int,long等,也可以是一个类的类名
当dataType是一个自定义类时,参考Api自定义类说明

  • required:是否必填
    值为true或false.
    当值为true时,Parameters表格的Parameter列与Description列为粗体,且value列的输入框显示required,该输入框为空时将会阻止提交操作

  • allowMultiple:允许多值
    值为true或false
    当为true时,输入框可使用”,”连接多个值,参数必须为数组或列表才可使用该属性

  • defaultValue :默认值
    该属性有值时,Parameters表格的value列输入框默认填入该值

  • allowableValues :允许的值的数组
    该属性有值时,Parameters表格的value列输入框将改为下拉列表,列表项为该值

@ApiResponses@ApiResponse


@ApiOperation(value = "say hello", notes="return Hello World")
@ApiResponses({
    @ApiResponse(code=500,message="失败"),
    @ApiResponse(code=501,message="内部异常")
})
@GetMapping("/say")
public String sayHello(@RequestParam String user){
    ...
}

@ApiModel

@ApiModelProperty

Swagger配置

全局参数

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(this.globalParameters());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot整合Swagger测试项目")
                .description("测试测试")
                .contact("yucoang")
                .version("1.0")
                .build();
    }
    private List<Parameter> globalParameters(){
        List<Parameter> aParameters = new ArrayList<Parameter>();
        ParameterBuilder p1 = new ParameterBuilder();
        p1
            .name("token")
            .description("token")
            .modelRef(new ModelRef("string"))
            .parameterType("header")
            .required(true)
            .defaultValue("")
            .build();
        aParameters.add(p1.build());
        return aParameters;
     }
}

全局返回值

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .globalResponseMessage(RequestMethod.GET,this.globalResponseMessage());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot整合Swagger测试项目")
                .description("测试测试")
                .contact("yucoang")
                .version("1.0")
                .build();
    }
    private List<ResponseMessage> globalResponseMessage(){
        List<ResponseMessage> aResponses = new ArrayList<>();
        aResponses.add(new ResponseMessage(201, "Created/已创建", null));
        aResponses.add(new ResponseMessage(401, "Unauthorized/未授权", null));
        aResponses.add(new ResponseMessage(403, "Forbidden/禁止", null));
        aResponses.add(new ResponseMessage(404, "地址不存在", null));
        return aResponses;
    }
}

分组

提供多个DocketSpring Bean,即可对Swagger进行分组

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("group1")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yucoang.controller"))
                .paths(PathSelectors.regex("/api/.*"))
                .build();
    }
    @Bean
    public Docket createRestApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("group2")
                .apiInfo(apiInfo2())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yucoang.controller2"))
                .paths(PathSelectors.regex("/nologin/.*"))
                .build();
    }
    private ApiInfo apiInfo() {
        ...
    }    
    private ApiInfo apiInfo2() {
        ...
    }
}

Swagger的资源文档设置

通过重写SwaggerResourcesProvider类,可重新定义Swagger的资源设置

@Configuration
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {


    @Autowired
    RefreshableRouteLocator refreshableRouteLocator;

    @Autowired
    YucoangCloudProperties yucoangCloudProperties;

    @Override
    public List<SwaggerResource> get() {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation("/demo01/v2/api-docs");
        swaggerResource.setSwaggerVersion(version);

        List<SwaggerResource> resourceList = new ArrayList<>();
        resourceList.add(swaggerResource);
        return resourceList;
    }

}

Swagger配置文件

# swagger接口访问地址
springfox.documentation.swagger.v2.host=http://address:port/projectname/

猜你喜欢

转载自blog.csdn.net/d292222100/article/details/81906680