Springboot——Swagger

Swagger2's maven dependency

To use the Swagger2 tool, you must import maven dependencies. The current official highest version is 2.8.0. I tried it. I personally feel that the page display effect is not very good, and it is not compact enough, which is not conducive to operation. In addition, the latest version is not necessarily the most stable version. We are currently using version 2.2.2 in our actual project. This version is stable and has a friendly interface. Therefore, this lesson mainly revolves around version 2.2.2. The dependencies are as follows:

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

Configuration of Swagger2

Using Swagger2 requires configuration. The configuration of Swagger2 in Spring Boot is very convenient. Create a new configuration class. In addition to adding the necessary @Configuration annotations to the Swagger2 configuration class, you also need to add the @EnableSwagger2 annotation.

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;
 
/**
 * @author shengwu ni
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定构建api文档的详细信息的方法:apiInfo()
                .apiInfo(apiInfo())
                .select()
                // 指定要生成api接口的包路径,这里把controller作为包路径,生成controller中的所有接口
                .apis(RequestHandlerSelectors.basePackage("com.itcodai.course06.controller"))
                .paths(PathSelectors.any())
                .build();
    }
 
    /**
     * 构建api文档的详细信息
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 设置页面标题
                .title("Spring Boot集成Swagger2接口总览")
                // 设置接口描述
                .description("跟武哥一起学Spring Boot第06课")
                // 设置联系方式
                .contact("倪升武," + "CSDN:http://blog.csdn.net/eson_15")
                // 设置版本
                .version("1.0")
                // 构建
                .build();
    }
}

In this configuration class, annotations have been used to explain the role of each method in detail, so I won't go into details here. So far, we have configured Swagger2. Now we can test whether the configuration is effective, start the project, enter localhost:8080/swagger-ui.html in the browser, and you can see the interface page of swagger2, as shown in the figure below, indicating that the integration of Swagger2 is successful.

Use of Swagger2

We have configured Swagger2 above, and started testing it, and the function is normal. Next, we will start using Swagger2, mainly to introduce several commonly used annotations in Swagger2, respectively on the entity class, the Controller class and the methods in the Controller. Finally, let's see how Swagger2 presents the online interface document on the page, and combine the methods in the Controller to test the data in the interface.

1. Entity class annotation

In this section, we build a User entity class, mainly introduce the @ApiModel and @ApiModelProperty annotations in Swagger2, and prepare for the subsequent tests.

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
 
@ApiModel(value = "用户实体类")
public class User {
 
    @ApiModelProperty(value = "用户唯一标识")
    private Long id;
 
    @ApiModelProperty(value = "用户姓名")
    private String username;
 
    @ApiModelProperty(value = "用户密码")
    private String password;
 
    // 省略set和get方法
}

Explain the @ApiModel and @ApiModelProperty annotations:

The @ApiModel annotation is used for entity classes, which means to describe the class, and is used for receiving parameters with entity classes.

The @ApiModelProperty annotation is used for attributes in the class, indicating the description of the model attribute or the change of data operation.

2. Relevant notes in the Controller class

Let's write a TestController, write a few more interfaces, and then learn the annotations related to Swagger2 in the Controller.

import com.itcodai.course06.entiy.JsonResult;
import com.itcodai.course06.entiy.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/swagger")
@Api(value = "Swagger2 在线接口文档")
public class TestController {
 
    @GetMapping("/get/{id}")
    @ApiOperation(value = "根据用户唯一标识获取用户信息")
    public JsonResult<User> getUserInfo(@PathVariable @ApiParam(value = "用户唯一标识") Long id) {
        // 模拟数据库中根据id获取User信息
        User user = new User(id, "倪升武", "123456");
        return new JsonResult(user);
    }
}

Let's learn @Api, @ApiOperation and @ApiParam annotations:

The @Api annotation is used on a class to indicate that this class is a swagger resource.

The @ApiOperation annotation is used on methods to represent the operation of an http request.

The @ApiParam annotation is used on parameters to indicate parameter information.

What is returned here is JsonResult, which is the entity encapsulated when learning to return json data in Lesson 02. The above are the five most commonly used annotations in Swagger. Next, run the project and enter localhost:8080/swagger-ui.html in the browser to see the interface status of the Swagger page.

It can be seen that the Swagger page displays the information of the interface very comprehensively. The function of each annotation and the place where it is displayed have been marked in the above figure, and all the information of the interface can be known through the page. Then we directly test the information returned by the interface online, enter the id as 1, and look at the returned data:

It can be seen that the data in json format is returned directly on the page, and developers can directly use this online interface to test whether the data is correct or not, which is very convenient. The above is for the input of a single parameter. If the input parameter is an object, what does Swagger look like? Let's write another interface.

@PostMapping("/insert")
    @ApiOperation(value = "添加用户信息")
    public JsonResult<Void> insertUser(@RequestBody @ApiParam(value = "用户信息") User user) {
        // 处理添加逻辑
        return new JsonResult<>();
    }

Restart the project, enter localhost:8080/swagger-ui.html in the browser to see the effect:

5. Summary

OK,本节课详细分析了 Swagger 的优点,以及 Spring Boot 如何集成 Swagger2,包括配置,相关注解的讲解,涉及到了实体类和接口类,以及如何使用。最后通过页面测试,体验了 Swagger 的强大之处,基本上是每个项目组中必备的工具之一,所以要掌握该工具的使用,也不难。

Guess you like

Origin blog.csdn.net/qq_39367410/article/details/128850555