springcloud:接口文档自动生成器swagger详解 上篇(十一)

0. 引言

在微服务的开发工作中,前后端的协同开发是必不可少的,随着服务数与接口数的增加,手写接口文档成为了一个苦活累活,很多程序员对此也很抵触。同时我们也需要有一个地方来统一管理这些接口。

一群比较懒的程序员会想能不能有一个工具自动生成这个接口文档呢,那么另外一群更懒的程序员就开发出了接口文档自动生成工具swagger

1. swagger介绍

swagger本质是一个web服务,用于生成、描述、调用REST风格的接口。除了接口文档,swagger还支持在线测试。直接在界面上输入参数值即可测试

现在实际生产中更多的使用整合了swagger的knife4j来进行接口文档的管理,但为了知识点的连贯性,我们先来学习swagger,knife4j我们后续再进行讲解

2. swagger使用

2.1 单个服务中引入swagger

1、在服务中添加swagger依赖


            io.springfox
            springfox-swagger2
            2.9.2

        

            io.springfox
            springfox-swagger-ui
            2.9.2

2、创建swagger配置文件SwaggerConfig

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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;

/**
 * @author whx
 * @date 2022/4/16
 */
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // api过滤器,设置哪些接口会加载创建接口文档
//                .apis(RequestHandlerSelectors.basePackage("com.xx.xx"))
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("商品服务接口文档")
                .description("商品服务接口文档说明:xxx")
                .contact(new Contact("55555", "", "[email protected]"))
                .version("1.0")
                .build();
    }

}

3、在实体类中添加说明
在实体类上使用注解@ApiModel
在字段上使用注解@ApiModelProperty

@Data
@ApiModel(value = "Product对象", description = "商品对象")
public class Product {

    @ApiModelProperty(value = "主键")
    private Long id;

    @ApiModelProperty(value = "商品名称")
    private String name;

    @ApiModelProperty(value = "商品编号")
    private String no;

    @ApiModelProperty(value = "商品价格")
    private Double price;

    @ApiModelProperty(value = "创建时间")
    private Date createTime;

}

4、controller中添加说明
在类上添加注解@Api,在方法上添加注解@ApiOperation

@RestController
@AllArgsConstructor
@Api(value = "商品Controller", tags = "商品接口")
public class ProductController {
    private final IProductService productService;

    @ApiOperation(value = "列表", notes = "无参数")
    @GetMapping("list")
    public List list(){
        return productService.list();
    }

    @ApiOperation(value = "保存", notes = "无参数")
    @PostMapping("save")
    public String save(){
        Product product = new Product();
        product.setId(555L);
        product.setName("商品xxx");
        product.setPrice(300.0);
        product.setNo("SP001");
        product.setCreateTime(new Date());
        int i = 1/0;
        return productService.save(product) ? "保存成功" : "保存失败";
    }
}

5、重启服务,访问localhost:9091/swagger-ui.html。这里的9091是该服务的端口号
springcloud:接口文档自动生成器swagger详解 上篇(十一)_第1张图片
点击对应的controller可以看到控制层中的接口,点击具体的接口可以看到接口的详细文档说明
springcloud:接口文档自动生成器swagger详解 上篇(十一)_第2张图片

3. 常用注解说明

@Api:说明类的作用。作用位置Controller
    tags="说明该类的作用,标签"
    value="接口说明"

@ApiOperation:说明接口/方法的作用。作用位置:Controller方法
    value="接口名"
    notes="接口备注"
    
@ApiModel:说明实体类。作用位置:实体类
	 value="实体类名称"
	 description="实体类描述"
    @ApiModelProperty:实体类字段说明。作用位置:实体类字段
     	value=“字段的中文说明”
		name=“字段名”
		notes=“字段备注”
		required=“是否必填”
		hidden=“是否隐藏,默认false,为true时在swagger中不显示”
		dataType=“数据类型,可以设置为String,Integer等”
		allowableValues=“允许值”
	    
@ApiImplicitParams:用在Controller方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,说明这个参数的各种信息
        name=“参数名”
        value=“参数的中文说明”
        required=“参数是否比天”
        paramType=“参数位置,比如如果参数来自header,那么其值为header”
            · header: 请求头参数 @RequestHeader
            · query: 普通请求参数 @RequestParam
            · path:路径请求参数 @PathVariable
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在Controller方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code=“状态码,例如400”
        message=“信息,例如‘请求参数没填好’”
        response=”抛出异常的类“

那么到此,我们针对单个服务的swagger配置就完成了。是不是很简单。

但是,大家有没有想到一个问题,如果我现在还有另外几个服务,那么我会就需要在每个服务中部署上述的步骤

那我们要访问不同服务的接口文档时,还要切换端口,很麻烦呀,有没有什么办法吧这些服务的端口文件归总到一个服务中,我们只需要访问一个端口就能看到所有服务的接口文档。

同时还记得我们第八章讲所有的nacosp配置文件集中到一个接口类中进行配置的理念吗?重复性的工作我们要减少,所以上述的swagger配置文件我们是不是也只用配置一遍呢?

那么下一期,我们开始配置真正的springcloud + swagger

关注公众号 Elasticsearch之家,了解更多新鲜内容

参考博客

https://zhuanlan.zhihu.com/p/161947638

你可能感兴趣的:(从零开始学习微服务,微服务,springcloud,swagger)