Spring Boot: elegant use of the API documentation tool Swagger2

Keywords: Java Spring SpringBoot xml

  1. introduction
    You must have been tortured by interface documents in the development process. Due to the lightweight and low coupling of RESTful interface, we did not update the documents in time after modifying the interface, resulting in frequent complaints from the interface callers (both front-end and back-end) about the inconsistency between the interface and the documents. The characteristic of programmers is that they don't like to write documents, but at the same time they don't like others to write documents. So the API documentation tool came into being. In this article, we will introduce the API documentation tool Swagger2.

  2. Get started quickly
    Since Swagger2 is an API documentation tool, let's take a look at how the documentation tool is used in Spring Boot in the code. (understand the source code and ask: 1791743380)

2.1 introduce dependency
Code listing: spring boot swagger/ pom.xml

<!-- swagger tool kit -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>

The version selected here is 2.9.2, which is also the latest version at present.

2.2 configuration class SwaggerConfig
Code listing: spring boot swagger / SRC / main / Java / COM / springboot / springbootswatger / config/ SwaggerConfig.java

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${swagger.show}")
    private boolean swaggerShow;

    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerShow)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.springbootswagger"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2 Demo interface RESTful APIs")
                .version("1.0")
                .build();
    }
}

Because Swagger is an API documentation tool, we can't open it in the production environment, so the author added swagger.show , configure different values in configuration files of different environments, or if there is a configuration center, this configuration can be added to the configuration center. The example here is added to the application for simplicity In the configuration file. In this way, we can turn on or off the function of Swagger gracefully.

2.3 entity class
Code listing: spring boot swagger / SRC / main / Java / COM / springboot / springbootswatger / model/ User.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "User presentation class", description = "Request parameter class")
public class User {
    @ApiModelProperty(example = "1", notes = "user ID")
    private Long id;
    @ApiModelProperty(example = "geekdigging", notes = "user name")
    private String nickName;
    @ApiModelProperty(example = "1570689455000", notes = "Creation time")
    private Date createDate;
    @ApiModelProperty(example = "18", notes = "User age")
    private Integer age;
}

Swagger note details:

API scope of application location
@ApiModel describes the meaning of the return object. It is used on the return object class
@ApiModelProperty object properties are used on the fields of the in and out parameter objects
@Api protocol set description is used on the controller class
@API operation protocol describes the methods used in the controller
@ApiResponses set is used on the method of controller
@ApiResponse Response is used in @ ApiResponses
@ApiImplicitParams non object parameter set is used in the method of controller
@ApiImplicitParam non object parameter description is used in @ ApiImplicitParams method
2.4 Controller
Code listing: spring boot swagger / SRC / main / Java / COM / springboot / springbootswatger / controller/ UserController.java

@Api(value = "User management presentation")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/getUserById/{id}")
    @ApiOperation(value = "Get user information", notes = "According to users id Get user information", tags = "Query user information class")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping("/getAllUsers")
    @ApiOperation(value = "Get all user information", notes = "Get all user information", tags = "Query user information class")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @PostMapping("/saveUser")
    @ApiOperation(value = "newly added/Modify user information")
    public User saveUser(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @DeleteMapping("/deleteById")
    @ApiOperation(value = "Delete user information", notes = "According to users id Delete user information")
    public String deleteById(@PathVariable Long id) {
        userService.deleteById(id);
        return "success";
    }
}

@Tag tag in ApiOperation can be used for interface grouping
2.5 the results are as follows
Start the project and open the browser to access: http://localhost:8080/swagger-ui.html , you can see the following page:

You can see our tag groups in this picture.

Posted by pk99 on Thu, 18 Jun 2020 18:55:13 -0700