Swagger的使用,包括swagger2和swagger3

Swagger的使用

1、建一个maven项目

2、引入依赖

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

springfox-swagger2:自动生成描述API的json文件
springfox-swagger-ui:用一种友好的界面呈现json文件

3、建一个SwaggerConfig配置文件

package com.zhou.swagger2.config;

import com.google.common.base.Predicates;
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.service.Contact;
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 webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .apis(RequestHandlerSelectors.basePackage("com.zhou"))
                .build();
    }
    private ApiInfo webApiInfo(){
        return new ApiInfoBuilder()
                .title("网站-中心API文档")
                .description("本文档描述了接口定义")
                .version("1.0")
                .contact(new Contact("hello", "https://blog.csdn.net/u013010499",
                        "[email protected]"))
                .build();
    }


}

4、建一个接口

package com.zhou.swagger2.controller;

import com.zhou.swagger2.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
@Api(tags="欢迎接口")
@RestController
@RequestMapping("/hello")
public class HelloController {

    @ApiOperation(value = "一个Rest")
    @RequestMapping(value = "request",method = RequestMethod.GET)
    public User rest(User user){
        return user;
    }

    @ApiOperation(value = "一个Get")
    @GetMapping("get")
    public User get(User user){
        return user;
    }

    @PostMapping("post")
    public User post(User user){
        return user;
    }

    @DeleteMapping("delete")
    public User delete(User user)
    {
        return user;
    }

    @PutMapping ("put")
    public User put(User user)
    {
        return user;
    }
}

5、建一个实体

package com.zhou.swagger2.entity;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class User {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "用户名")
    private String userName;
    @ApiModelProperty(value = "年龄")
    private int age;
}

6、运行

Swagger的使用,包括swagger2和swagger3_第1张图片
点开一个接口,输入参数收点击 try it out
Swagger的使用,包括swagger2和swagger3_第2张图片
这是返回的结果
Swagger的使用,包括swagger2和swagger3_第3张图片

swagger3

它与swagger2的差异在于

  • 配置文件上添加的注解是@EnableOpenApi而swagger2是@EnableSwagger2
  • 访问地址http://localhost:8080/swagger-ui/index.html 而swagger2是http://localhost:8080/swagger-ui.html
  • pom引入的文件只有一个 springfox-boot-starter
    而swagger2有两个springfox-swagger2 springfox-swagger-ui

下面直接介绍怎么用

1、在pom文件中引用

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

2、建配置类

package com.zhou.swagger3.config;

import io.swagger.v3.oas.annotations.Operation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.schema.ScalarType;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

@EnableOpenApi //启用swagger
@Configuration
public class Swagger3Config implements WebMvcConfigurer {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class)) //只有在接口上加了Operation注解才展示
                .paths(PathSelectors.any())
                .build()
                //.globalRequestParameters(getGlobalRequestParameters())
                .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
                .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("联系")
                .contact(new Contact("牧歌ing", "https://blog.csdn.net/u013010499", "[email protected]"))
                .version("1.0")
                .build();
    }

    private List<Response> getGlobalResonseMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
         return responseList;
    }
}

3、建一个接口文件

package com.zhou.swagger3.controller;

import com.zhou.swagger3.entity.User;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.*;

@Api(tags="欢迎接口")
@RestController
@RequestMapping("/hello")
public class HelloController {

    @Operation(summary = "一个Rest") //接口的备注信息
    @RequestMapping(value = "request",method = RequestMethod.GET)
    public User rest( User user){
        return user;
    }

    @Operation(summary = "一个Get")  //接口的备注信息
    @GetMapping("get")
    public User get(User user){
        return user;
    }

    @PostMapping("post")
    public User post(User user){
        return user;
    }

    @DeleteMapping("delete")
    public User delete(User user)
    {
        return user;
    }

    @PutMapping ("put")
    public User put(User user)
    {
        return user;
    }
}

4、建一个实体类

package com.zhou.swagger3.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel("用户")
public class User {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "用户名")
    private String userName;
    @ApiModelProperty(value = "年龄")
    private int age;
}

application.properties

# 在测试环境中用到,生产环境需设置为false
springfox.documentation.swagger-ui.enabled=true
server.port=8081

5、运行

Swagger的使用,包括swagger2和swagger3_第4张图片
输入参数,点击execute
Swagger的使用,包括swagger2和swagger3_第5张图片
返回结果
Swagger的使用,包括swagger2和swagger3_第6张图片

一些常用的注解

swagger2 swagger3 注解位置
@Api(tags=“接口描述”) @Api(tags=“接口描述”) controller类上
@ApiOperation(value = “接口方法描述”) @Operation(summary = “接口方法描述”) controller 方法上
@ApiModelProperty(value = “字段描述”) @ApiModelProperty(value = “字段描述”) JavaBean的字段上
@ApiModel(“实体类的描述”) @ApiModel(“实体类的描述”) JavaBean上
@EnableSwagger2 @EnableOpenApi 配置类上
@ApiImplicitParams @ApiImplicitParams controller的方法参数中
@ApiImplicitParam @ApiImplicitParam @ApiImplicitParams 下的的子参数
@ApiParam(name = “参数描述”) @Parameter(description = “参数描述”) controller 方法的参数中

项目地址:https://gitee.com/daijianzhou/swagger

你可能感兴趣的:(工具,restful,java,spring,swagger,intellij,idea)