SpringBoot系列:六、集成Swagger文档

本篇开始介绍Api文档Swagger的集成

一、引入maven依赖

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

二、添加Spring依赖注入Bean

@Configuration
public class Swagger {

    @Bean
    public Docket createRestApi(){
        return  new Docket(DocumentationType.SWAGGER_2)
//文档基础设置信息 .apiInfo(apiInfo()) .select()
//要扫描的包 .apis(RequestHandlerSelectors.basePackage(
"com.example.demo.controller"))
//路径显示规则any全部显示,可以选择正则方式来匹配自己想要显示的接口 .paths(PathSelectors.any()) .build(); }
private ApiInfo apiInfo(){ return new ApiInfoBuilder()
//文档标题会展示在文档最上方加大加粗显示 .title(
"Swagger文档")
//会显示在标题下的一段描述 .description(
"resultful文档")
//文档版本号 .version(
"1.0") .build(); } }

三、在接口上设置注解

Swagger遵循resultFul规范,会根据请求方式来生成文档,所以这里的RequestMapping必须指定

明确的Http请求方式。例如:PostMapping/GetMapping

如果使用RequestMapping,Swagger会把每种请求都生成一个文档 

常用注解列表:

- @Api()用于类;
用来描述当前Controller的信息
- @ApiOperation()用于方法;
用来描述当前接口的信息
- @ApiParam()用于方法,参数,字段说明;
用来描述接口中的参数
- @ApiModel()用于类
用于描述接口中实体类的
- @ApiModelProperty()用于方法,字段
用于描述实体类属性
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

四、访问swagger地址

应用路径/swagger-ui.html

原文地址:https://www.cnblogs.com/Tassdar/p/12101295.html