springcloud: Detailed explanation of the interface document automatic generator swagger Part 1 (11)

0 Preface

In the development of microservices, the collaborative development of front and back ends is essential. With the increase in the number of services and interfaces, handwritten interface documentation has become a chore, and many programmers are also very resistant to this. At the same time, we also need a place to manage these interfaces in a unified manner.

A group of lazy programmers wondered if there could be a tool to automatically generate this interface document, then another group of lazy programmers developed the interface document automatic generation tool swagger

1. Introduction to swagger

Swagger is essentially a web service for generating, describing, and calling REST-style interfaces. In addition to interface documentation, swagger also supports online testing. Enter parameter values ​​directly on the interface to test

Now in actual production, knife4j that integrates swagger is used to manage interface documents, but for the consistency of knowledge points, let's learn swagger first, and knife4j will be explained later.

2. Using swagger

2.1 Introducing swagger into a single service

1. Add swagger dependencies to the service

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

2. Create the swagger configuration file 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. Add a description
to the entity class Use annotations on entity classes Use annotations @ApiModel
on fields@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. Add a description
to the controller Add annotations to classes and @Apimethods to add annotations@ApiOperation

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

    @ApiOperation(value = "列表", notes = "无参数")
    @GetMapping("list")
    public List<Product> 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. Restart the service and visit localhost:9091/swagger-ui.html. Here 9091 is the port number of the service.
insert image description here
Click the corresponding controller to see the interface in the control layer, and click the specific interface to see the detailed documentation of the interface.
insert image description here

3. Common annotations

@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=”抛出异常的类“

So at this point, our swagger configuration for a single service is complete. Is not it simple.

However, have you ever thought of a question, if I have several other services now, then I will need to deploy the above steps in each service

Then when we want to access the interface documents of different services, we have to switch ports, which is very troublesome. Is there any way to summarize the port files of these services into one service? We only need to access one port to see all the services. Interface documentation.

At the same time, do you still remember the concept that we talked about in Chapter 8 that all nacosp configuration files are centralized in one interface class for configuration? We need to reduce the repetitive work, so do we only need to configure the above swagger configuration file once?

Then in the next issue, we start to configure the real springcloud + swagger

Follow the official account Elasticsearch home to learn more fresh content

Reference blog

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

Guess you like

Origin blog.csdn.net/qq_24950043/article/details/124237064