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.

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 / springbootswatgger / 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 adds swagger.show in the configuration, and configures different values in the 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 in the application configuration file for the sake of simplicity. . 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 / springbootswatgger / 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 action Use location
@ApiModel Describe the meaning of the returned object Used on return object class
@ApiModelProperty Object attribute Used on the fields of the access parameter object
@Api Protocol set description Used on the controller class
@ApiOperation Protocol description Used in the method of controller
@ApiResponses Response set Used in the method of controller
@ApiResponse Response Used in @ ApiResponses
@ApiImplicitParams Non object parameter set Used in the method of controller
@ApiImplicitParam Non object parameter description Used in @ ApiImplicitParams method

2.4 Controller

Code list: spring boot swagger / SRC / main / Java / COM / springboot / springbootswatgger / 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.

3. Example code

Sample code Github

Sample code - Gitee

4. reference

https://blog.csdn.net/xupeng8...

If my article is helpful to you, please scan the code and pay attention to the author's public number: get the latest dry goods push:)

Posted by flOid on Wed, 16 Oct 2019 19:48:38 -0700