Spring Boot 2.x: The Correct Play of Swagger 2

Keywords: Java Attribute Spring github

Introduction to Swagger 2

Simply put, Swagger2 was born to solve the pain point of API document maintenance when front-end and back-end developers communicate. It can be perfectly integrated with our Java program and can be used in conjunction with Spring Book, another of our development tools.

Start using

Step 1: Import the POM file

         <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency> 
        
        <!-- Use here swagger-bootstrap-ui Instead of the original ugly uiļ¼ŒSave Virgo~ -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.0</version>
        </dependency>

#### Step 2: Add configuration classes

We need to add a Swagger2Config configuration class:

/**
 *    Swagger2 Configuration class
 * @author vi    
 * @since 2019/3/6 8:31 PM
 */
@Configuration
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("indi.viyoung.viboot.*"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("viboot-swagger2")    //Title
                .description("Restful-API-Doc")    //describe
                .termsOfServiceUrl("https://www.cnblogs.com/viyoung"// / The service website is configured here. My blog site is ~Welcome to pay attention to it.~
                .contact(new Contact("Vi Technology Blog", "https://Www.cnblogs.com/viyoung,""18530069930@163.com")//The three parameters are name, personal website and mailbox in turn.
                .version("1.0") //Edition
                .build();
    }
}

Step 3: Add a configuration to the startup class

Note that you must remember to add the @EnableSwagger2 annotation

/**
 * @author vi
 * @since 2019/3/6 6:35 PM
 */
@SpringBootApplication
@ComponentScan(value = "indi.viyoung.viboot.*")
@MapperScan(value = "indi.viyoung.viboot.swagger2.mapper")
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class ViBootSwaggerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ViBootSwaggerApplication.class, args);
    }
}

Step 4: Complete API documentation with annotations

1. @Api
Annotation Name Annotation Properties Scope Attribute function
@Api tags class Explain the role of this class
value class Explain the role of this class

For example:

@Api(value = "User Class Controller",tags="User Class Controller")
public class UserController {
...
}

2 . @ApiOperation
Annotation Name Annotation Properties Scope Attribute function
@ApiOperation() value Method Descriptive Method Function
notes Method Tips
tags Method Grouping

For example:

     @ApiOperation(value = "Get the user list",notes = "Get the user list")
    public List<User> get() {
         ...   
    }

3. @ApiParam
Annotation Name Annotation Properties Scope Attribute function
@ApiParam() name Method parameters Parameter name
value Method parameters Description of parameters
required Method parameters Is it necessary to fill in

For example:

    @ApiOperation(value="Get user details", notes="according to url Of id To get user details")
    public User get(@ApiParam(name="id",value="user id",required=true) Long id) {
        log.info("GET..{}...Method execution...",id);
        return userService.getById(id);
    }

4. @ApiModel && @ApiModelProperty
Annotation Name Annotation Properties Scope Attribute function
@ApiModel() value class Object name
description class describe
@ApiModelProperty() value Method Field description
name Method Property name
dataType Method Attribute type
required Method Is it necessary to fill in
example Method Give an example
hidden Method hide

For example:

@ApiModel(value="user object",description="User Object user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    @ApiModelProperty(value = "user ID",example = "1000001",hidden=true)
    private Long id;

    @ApiModelProperty(value="User name",required = true,dataType = "String")
    private String userName;
    
    @ApiModelProperty(value = "Password")
    private String password;
}

5. @ApiImplicitParam && @ApiImplicitParams
`@ ApiImplicitParam `can be used for method supremacy alone. For multiple parameters, `@ApiImplicitParam'can be placed in `@ApiImplicitParams', where only `@ApiImplicitParam' properties are listed:
Annotation Name Annotation Properties Scope Attribute function
@ApiImplicitParam() value Method Description of parameters
name Method Parameter name
dataType Method data type
paramType Method Parameter type
example Method Give an example

For example:

    @ApiImplicitParams({
            @ApiImplicitParam(name = "user", value = "User entity user", required = true, dataType = "User")
    })
    public void put(User user) {
        userService.updateById(user);
        log.info("PUT Method execution...");
    }

One thing to note here is that we did not write two parameters in the circle in the annotation. This is to read the annotation we just made for the User class and set the user name to be required!

6.@ApiResposne && @ApiResponses

@ The relationship between ApiResponses and @ApiResponse and the relationship and usage of @ApiImplicitParam & & @ApiImplicitParams are similar.

Annotation Name Annotation Properties Scope Attribute function
@ApiResponse() response Method Return class
code Method Return code
message Method Return information
examples Method Example

Finally, let's talk about this UI.

Start by posting a couple of spring-fox UIs (which we know well)

Believe to see here, you should have an answer to the choice of these two sets of UI, of course, bootstrap style UI is not only beautiful, but also has a variety of powerful functions.~

  1. Export md documents

  1. Parameter caching

Public Number

The original articles are limited in writing and have little knowledge. If there are any errors in the articles, please let us know.

Posted by danrl on Tue, 06 Aug 2019 19:06:20 -0700