tags: springboot swagger doc


In a word: For product development, especially the development mode of front and back end separation, the interface document is the hub connecting the front and back end. This paper describes the practice of Springboot + Swagger in enterprises in detail.

1. The introduction

In the process of software development, interface design and interface documentation is an important link, especially in the case of separation of front and back ends, interface documentation is the connection point between developers. There are many ways to prepare the interface document, you can use Word, you can also use writing tools such as small chicken, these basically belong to the document written from the code, if the interface changes, the need to modify the document, increase the workload. How to improve the efficiency of the interface document written in springboot development, combined with the swagger to provide the interface documentation is a good practice, through the configuration and annotations, in the process of interface code, write the interface document at the same time, the interface needs to change, the document also change at the same time, with little quantity, high efficiency, intuitive interface document is concise, Benefits such as real-time invocation of validation. In this paper, the basic Springboot2 + Swagger2, combined with the practice in the enterprise, the writing of the interface document is described in detail, including the following contents:

  • Swagger introduction and documentation generation description
  • Build the sample project and configuration description using SpringBoot2 + Swagger2
  • Use annotations to add documentation content
  • Use global parameters for interface authentication

If you want to see the source code, this paper sample address: https://github.com/mianshenglee/my-example

2. Introduction to swagger

2.1 introduce swagger

Swagger official website address: https://swagger.io, from the official website, it is a Specification (OpenAPI Specification, OAS) and complete framework (such as Editor Swagger Editor, display component Swagger Editor, Code Generation Swagger Codegen) for generating, describing, invoking, and visualizing RESTful Web services. Since it is a specification, it defines a set of rules related to interface description, such as document format, file structure, data types, request methods, etc. Please refer to the official specification: https://swagger.io/specification/v2/, file design and writing are generally YAML formats (convenient), will be used in the transmission JSON (view). After a interface description file, need to be friendly, according to swagger provides a swagger UI: https://swagger.io/tools/swagger-ui/. The purpose of this component is to display a yamL file that has been written to the specification as an interface document. We can download this component to run locally, which is a static web page and run it in a Web container (such as Apache, nginx). You can also use the online version of the official website. As follows:

So far, we know that the steps of using swagger to write interface documents are :(1) write interface files conforming to OAS, (2) display them using swagger- UI.

2.2 Springfox, Swagger and Springboot

As we can see from the above, interface files in line with OAS still have to be compiled manually, and Swagger-UI display is not convenient (manual offline deployment or online service is required). Now web development in Java field basically uses SpringMVC development, is there a more convenient way to write interface files with Swagger? Without having to write it by hand?

Cattle people Marty Pitt swagger-springmvc:https://github.com/martypitt/swagger-springmvc-example wrote a Spring based components, Used to integrate Swagger into SpringMVC. Springfox evolved from this component to automatically generate JSON API documents based on Spring, Now through https://github.com/martypitt/swagger-springmvc/ address will jump straight to the springfox making page, it’s website: http://springfox.io. Springfox-swagger2 has been released in several versions. This article uses springfox-Swagger2 version 2.7.0. For Swagger-UI, it also provides Springfox-Swagger-UI, integrated interface document display page. In this way, both of the previous Swagger steps can be done automatically. But now we develop Java Web applications are basically using SpringBoot for development, using its automatic configuration and annotations, more convenient development. Therefore, based on the Swagger specification, using SpringFox’s components (Swagger2 and Swagger-UI) in conjunction with SpringBoot, interface documentation can be very simple and efficient. In general, SpringFox is an automated implementation of the Swagger specification in SpringMVC and SpringBoot development. In the following part of this paper, specific usage is described in this way.

3. Use SpringBoot + Swagger to build interface documents

This section builds the sample project using SpringBoot2 + Swagger2 and describes the basic configuration.

3.1 Springboot example project construction

(1) Create a project: generate an empty Spring Boot project through the Spring Initializr page and add web dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Copy the code

(2) Write sample interface:

  • First add several general packages: VO, Controller, Service, Model, exception, respectively store the view layer model, control layer, service layer, data model layer, exception object code.
  • The sample data model is User, with UserController, UserService, uniformly return ResponseResult, uniformly return exception class UniRuntimeException.
  • For user management, restful interfaces are used to define user add,DELETE, modify, and query, corresponding to (POST,DELETE,PUT, and GET requests), as follows:
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    /** * Query a single user */
    @GetMapping("/{userId}")
    public ResponseResult getUserById(@PathVariable long userId) {... }/** * Query multiple users */
    @GetMapping(a)public ResponseResult getUsers(a) {... }/** * Add multiple users */
    @PostMapping(a)public ResponseResult addUsers(@RequestBody List<User> users) {... }/** * Add a single user */
    @PostMapping("/user")
    public ResponseResult addUser(@RequestBody User user) {... }/** * Update single user */
    @PutMapping("/user")
    public ResponseResult updateUser(@RequestBody User user) {... }/** * Delete a single user */
    @DeleteMapping("/user")
    public ResponseResult deleteUser(long userId) {...}
}
Copy the code

Note: here we focus on the definition of the interface, the parameters and return values, specific entity not listed (to see the source code in detail: https://github.com/mianshenglee/my-example).

At this point, the sample project is up and running with the following interfaces:

  1. GET /users/{userId}Obtaining a single user
  2. GET /usersGet multiple users
  3. POST /usersAdding Multiple Users
  4. POST /users/userAdding a User
  5. PUT /users/userUpdating a Single user
  6. DELTE /users/user? userId=xxDeleting a User

Note: RequestMapping interface, if you do not specify httpMethod, springfox will take all actions of this method, the GET/POST/PUT/PATCH/DELETE methods are listed, so write interface, please specify the actual action.

3.2 Introduction of Swagger2 and Basic Configuration

3.2.1 Add Springfox-Swagger dependency

To automate the generation of swagger compliant interface description files, add springFox dependencies as follows:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
Copy the code

3.2.2 configuration swagger

Add config package to store configuration files, add the following swagger2config.java configuration as follows:

@Configuration
@EnableSwagger2
public class Swagger2Config {
private ApiInfo apiInfo(a) {
	@Bean
	public Docket api(a){
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.any())
				.paths(PathSelectors.any())
				.build();
	}
    private ApiInfo apiInfo(a) {
		return new ApiInfoBuilder().title("Interface Description Document")
				.description("API Documentation Description")
				.version("0.0.1 - the SNAPSHOT") .build(); }}Copy the code

This file configures the Docket Bean, including the basic API information, apis to display, and paths to filter, so that the interface document can be generated in compliance with the specification.

3.2.3 View Swagger automatically Generated Description Document

After using the above configuration integrated swagger2, start the program, enter http://localhost:8080/swaggerdemo/v2/api-docs to view the JSON format interface description document. As follows:

This document conforms to the OAS specification, but there is still a step to visualization and use, which is how to present this information on the interface.

3.3 Adding Swagger-UI Interface Interaction

To visually display interface documents, SpringFox has provided an interface display component, adding the following dependencies:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
Copy the code

Introduced, after adding this dependence springfox – swagger – UI. Jar package have swagger – UI. HTML page, use the address http://localhost:8080/swaggerdemo/swagger-ui.html can see interface documentation page. In this document, you can view the interface definition, input parameters, return values, or debug by calling the interface using try it out. As follows:

So far, through the previous example, the automatic generation and UI display of interface documents using Swagger has been realized in the simplest way. However, there is still a certain distance compared with the actual development and use of interface documents in enterprises, including:

  • Documents cannot be displayed depending on the environment (they may be required in the development environment, but not in the formal environment)
  • The interface has no function description or detailed description
  • Input parameter description and example description
  • A detailed description of return values and an example description
  • All controller interfaces are returned, and no interfaces are filtered on demand
  • All interfaces can be debugged, and there are permission authentication problems

These problems need to be dealt with in enterprise practice.

4. [Enterprise practice] Configure parameterization and packet filtering

4.1 Configuring Parameters

An interface document, usually about the basic information of this document, including the document title, description, interface version, contact information, such as swagger has provided the corresponding configuration items, such as in the following example apiInfo (), write the basic information is configured in the code, this is not friendly to modify, therefore, it is best to put these configuration parameters, Form a separate configuration file for Swagger to avoid code changes caused by modifying basic information.

4.1.1 Adding a Basic Information Configuration File

In the Resources /config directory, add swagger.properties file and put the configuration information into this file.

Swagger. BasePackage = me. Mason. Helloswagger. Demo. The controller swagger. Title = application API documentation swagger. The description = API document description Version = 0.0.1-SNAPSHOT swagger.enable = true Swagger. contactName = Mason swagger.contactEmail = swagger.contactUrl = swagger.license = swagger.licenseUrl =Copy the code

In the config package, add SwaggerInfo object corresponding to the above configuration file:

@Component
@ConfigurationProperties(prefix = "swagger")
@PropertySource("classpath:/config/swagger.properties")
@Data
public class SwaggerInfo {
    private String basePackage;
    private String antPath;
    private String title = "HTTP API";
    private String description = "Swagger automatically generates interface documents";
    private String version ;
    private Boolean enable;
    private String contactName;
    private String contactEmail;
    private String contactUrl;
    private String license;
    private String licenseUrl;
}
Copy the code

It is recommended to add the following spring-boot-configuration-processor dependencies to generate configuration metadata for this custom configuration. Otherwise, in IDEA, – Spring Boot Configuration Annotation Processor not found in classpath

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
Copy the code

4.1.2 Integrating and Configuring the Swagger Document

With the SwaggerInfo configuration class, the apiInfo() integrated with Swagger2 can be injected and used to modify the configuration file if needed later.

private ApiInfo apiInfo(a) {
    return new ApiInfoBuilder().title(swaggerInfo.getTitle())
        .description(swaggerInfo.getDescription())
        .version(swaggerInfo.getVersion())
        .licenseUrl(swaggerInfo.getLicenseUrl())
        .contact(
            new Contact(swaggerInfo.getContactName()
            ,swaggerInfo.getContactUrl()
            ,swaggerInfo.getContactEmail()))
        .build();
}
Copy the code

4.2 Configuring whether to Enable documents

Interface documentation may need to be enabled and disabled for different environments, for example, in a development environment we need to display interface documentation, but in a formal online environment, sometimes we don’t want to expose interfaces to the public. This requirement can be configured using the enable command, combined with the swagger. Enable configuration item (false disables swagger, true enables Swagger) in the configuration file. As follows:

.enable(swaggerInfo.getEnable())
Copy the code

4.3 packet filter

The Swagger component automatically scans interfaces with Controller annotations and RequestMapping annotations and translates them into interface descriptions. During development, we don’t want all the interfaces in the project to be displayed, but rather the interfaces under a particular package. You can do this using method apis(), combined with configuration files. Swagger. BasePackage configuration in config file (multiple packages use “;” Separated). Add the following filter functions:

private List<Predicate<RequestHandler>> apisFilter() {
    List<Predicate<RequestHandler>> apis = new ArrayList<>();
    String basePackageStr = swaggerInfo.getBasePackage();
    / / packet filter
    if (StrUtil.isNotEmpty(basePackageStr)) {
        // Support multiple packages
        String[] basePackages = basePackageStr.split(";");
        if (null! = basePackages && basePackages.length >0) {
            Predicate<RequestHandler> predicate = input -> {
                // Filter by basePackageClass<? > declaringClass = input.declaringClass(); String packageName = declaringClass.getPackage().getName();returnArrays.asList(basePackages).contains(packageName); }; apis.add(predicate); }}return apis;
}
Copy the code

The preceding function compares the scanned interface with the configured packet. If the configured packet is displayed, the packet is returned. Otherwise, the packet is filtered out. Then add this filter when you configure the Docket.

builder = builder.apis(Predicates.or(apisFilter()));
Copy the code

Predicates. Or is used here, indicating that the returned or operation is performed, and true is displayed.

5. Use annotations to add document content

With the configuration above, we have the flexibility to build documents. However, the content of the document is not rich, and the description of the interface is not detailed. Springfox describes the interface through annotations, including the following annotations:

  1. Data model annotations:@ApiModel, entity description;@ApiModelProperty, entity attribute description
  2. Interface notes:@ApiOperation, interface description;@ApiIgnore, ignore this interface
  3. Controller notes:@Api, Controller description
  4. Input parameter notes:@ApiImplicitParams, interface multiple parameters;@ApiImplicitParam, single parameter;@ApiParam, single parameter description
  5. Comments on response data:@ResponseHeader, the response value header;@ApiResponses, response value set;@ApiResponse, a single response value

Let’s explain the use of annotations and use them to add the interface description in the example.

5.1 Data Model (Model) Notes

In the development process, M (Model) is used for data communication of the INTERFACE of MVC pattern. Therefore, it is necessary to describe the data Model effectively. The corresponding notes are:

  • @ApiModel: Entity Description
  • @ApiModelProperty: Entity attribute description.

The following table shows the instructions for the use of @APIModelProperty:

Annotation properties type describe
value String Field description.
name String Overwrite the field name.
dataType Stirng Overwrite the field type.
required boolean Mandatory or not.
example Stirng Give an example.
hidden boolean Whether to hide the field in the document.
allowEmptyValue boolean Whether to allow null.
allowableValues String The value allowed for this field.

In this example, the User class, is described with the following annotation:

@ApiModel
public class User {
    @ApiModelProperty(value="id",required = true,example = "1")
    private long id;
    @ApiModelProperty(value="Name",required = true,example = "Zhang")
    private String name;
    @ApiModelProperty(value="Age",example = "10")
    private int age;
    @ApiModelProperty(value="Password",required = true,hidden = true)
    private String password;
}
Copy the code

Thus, in the interface document, when User is used as an input parameter, you can see the following description of the model:

5.2 Controller and Interface Notes

When SpringFox automates document generation without annotations, controllers and interfaces basically display code class names, method names, and interface mappings. The following describes the controller and a specific interface:

  • @APIIgnore: The Swagger document does not show the interface that has this annotation

  • @Api: description of the controller

Annotation properties type describe
tags String[] Controller label.
description String Controller description (this field is declared expired).
  • @ApiOperation: Description of the interface.
Annotation properties type describe
value String Interface description.
notes String Interface release description.
tags Stirng[] The label.
response Class<? > Interface return type.
httpMethod String Interface request mode.

In this example, it is described in UserController as follows:

@Api(tags = "User Management Interface", description = "User Controller")
public class UserController {
    @ApiOperation(value = "Get individual user information by ID", notes = "Return user object by ID").../ / to omit
 @ApiOperation(value = "Add multiple users", notes = "Add multiple users as an array using JSON").../ / other
}
Copy the code

Using these annotations, the document appears as follows:

5.3 Comments on Interface Input Parameters

5.3.1 Use of SpringMVC controller parameters

Before introducing Swagger’s interface input parameter annotations, it is necessary to have a clear understanding of SpringMVC interface parameters. We know that SpringMVC uses @requestMapping to map methods to request urls, and that interface methods need to be called with parameters passed to the controller. In general, SpringMVC parameter passing includes the following:

  • No annotation parameter
  • @RequestParamAnnotation parameters
  • Array parameter
  • JSON object parameters
  • REST Style Parameters

For easy explanation, the ParamDemoController file is provided in this example, which provides various parameter examples. You can refer to the following parameters.

(1) No annotation parameter

The parameter name must be the same as the HTTP request parameter name. The parameter can be empty. The following interfaces:

@GetMapping("/no/annotation")
public Map<String,Object> noAnnotation(Integer intVal, Long longVal, String str){}
Copy the code

When calling, can use http://localhost:8080/no/annotation? InVal =10&longVal=100, the STR argument can be null.

(2)@RequestParamAnnotation parameters

Using the annotation RequestParam to get the parameters, you can specify a mapping between HTTP parameters and method parameter names that cannot be null (although null can be allowed by setting false to required). The following interfaces:

@GetMapping("/annotation")
public Map<String,Object> annotation(@RequestParam("int_val") Integer intVal,@RequestParam("long_val") Long longVal,@RequestParam(value="str_val", required = false) String str){}
Copy the code

The call method is the same as above without annotations. But if required=false is not set, the STR argument must be passed.

(3) Array parameters

Using an array as an argument, the interface is called with the array elements separated by commas (,). The following interfaces:

@GetMapping("/array")
public Map<String,Object> requestArray(int[]intArr,long[]longArr,String[] strArr){}
Copy the code

Call this interface, can use http://localhost:8080/array? IntArr = 10 final three & longArr = 100101102 & strArr = a, b, c.

(4) JSON object parameters

When the data transferred is relatively complex or related to the defined model, the parameters need to be assembled into JSON and passed. The front-end interface calls the JSON RequestBody. SpringMVC can use the @requestbody annotation to map the JSON parameters and perform the appropriate object conversion. As follows:

@PostMapping("/add/user")
public User addUser(@RequestBody User user){}
Copy the code

When the interface is called, the parameters are passed in JSON, obtained via the RequestBody annotation, and the mapping is converted to a User object. The same is true for array (List) objects.

(5) REST style parameters

For RESTFUL urls, parameters are written in the URL, such as Users /1, where 1 is the user ID parameter. For such arguments, SpringMVC implements @pathVariable with {} as placeholders. As follows:

@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long id){}
Copy the code

5.3.2 Swagger Input Parameters Remarks

Springfox has done automatic processing for the SpringMVC arguments mentioned above and will display them based on their type when displayed in the Swagger-UI document. In Swagger, parameter types are:

  • Path: submits data in the form of an address, which is used by the interface that queries users by ID
  • Query: The parameter is passed as a query string, corresponding to no annotation and@RequestParamAnnotation parameters
  • Header: Parameters in the request header
  • Form: Submitting a form, such as uploading a file, falls into this category
  • Body: The parameter is passed in JSON mode

When describing input parameters, Swagger is annotated in the following:

  • @ApiImplicitParams: Describes the parameter set of the interface.
  • @ApiImplicitParam: Describes an interface parameter, and@ApiImplicitParamsUse in combination.
  • @ApiParam: Describes a single parameter. It is optional

Where, @APIParam is used together with a single parameter, and @APIIMPLICITParam is used in the interface description. The attributes of the two parameters are basically the same. The @apiIMPLicitParam properties are as follows:

Annotation properties describe
paramType The query parameter type, which indicates where the parameter is located, can be: path, query, header, form, or body.
dataType The data type of the parameter is only used as a flag and is not verified. You can set the value as the actual type, for example, String or User
name Parameter name
value Parameter meaning description
required Yes/No Mandatory: true/false
allowMultiple Whether there are multiple objects, used when using JSON array objects
example The data sample

Here is the interface to using an array of JSON objects as parameters, as follows:

@ApiOperation(value = "Add multiple users", notes = "Add multiple users as an array using JSON")
@ApiImplicitParams({
    @ApiImplicitParam(name = "users", value = "User JSON array", required = true, dataType = "User",allowMultiple = true)})@PostMapping(a)public ResponseResult addUsers(@RequestBody List<User> users) {}
Copy the code

In this example, the @requestBody annotation is used to pass the JSON array parameters of List

, so the allowMultiple attribute is used, dataType is User, and its paramType is body. The swagger file is as follows:

5.4 Comments on Interface Response Data

For controllers that use the @RestController annotation, SpringMVC automatically converts the returned data to JSON data. During the development process, we generally encapsulate the returned data, return status, information, actual data, and so on. In this example, ResponseResult is used as the uniform return result, and the returned data is generic (if generic is not used, then swagger will not be displayed for Model attributes when displaying the returned result), as follows:

@NoArgsConstructor
@AllArgsConstructor
@Data
public class ResponseResult<T> {
	@ApiModelProperty(value="Return status",example = "true")
	private boolean success;
	@ApiModelProperty(value="Error message code")
	private String errCode;
	@ApiModelProperty(value="Error display information")
	private String errShowMsg;
	@ApiModelProperty(value="Error message")
	private String errMsg;
	@ApiModelProperty(value = "Return data",notes = "Null or error message object if error message is returned.")
	private T resultData;
}
Copy the code

If the interface returns a ResponseResult and does not specify a specific Model, only the ResponseResult will be displayed, and the contents of the specific resultData will not be displayed, as follows:

Therefore, for uniform returns, you need to specify the specific returned model so that there is a description of the actual returned model. As follows:

@ApiOperation(value = "Get all users", notes = "Return all users")
@GetMapping(a)public ResponseResult<List<User>> getUsers() {}
Copy the code

For response messages, swagger provides a default response message of 401,403,404, or it can be specified for the interface itself.

  • @ApiResponses: Response message set
  • @ApiResponses: Response message, describing an error response message, and@ApiResponsesUsed together
  • @ResponseHeader: Response header Settings

6. [Enterprise practice] Interface authentication

Generally, permission verification is required for the advertised interfaces. Only the login user can invoke the interfaces. Otherwise, insufficient permissions are reported. For the safety of the API certification, generally has the following several patterns (refer to swagger document: https://swagger.io/docs/specification/authentication/) :

  • Basic authentication: UseAuthorizationRequest headers, user names, and passwords are Base64 encoded, such as:Authorization: Basic ZGVtbzpwQDU1dzByZA==
  • Bearer of authentication: UseAuthorizationRequest header: the server generates an encrypted character token. When the client sends a request, it sends the request of this token to the server as a certificate. The token format isAuthorization: Bearer <token>
  • API Keys authentication: use request headers, parameters, or cookies to transfer Keys known only to the client and server.
  • OAuth2: An open standard that allows users to authorize third party mobile applications to access their information stored on another service provider without having to provide user names and passwords to third party mobile applications or share all the content of their data.

For the springboot projects separated from the front and back ends, many of the JWT authentication methods (Bearer authentication) are adopted, in which tokens need to be obtained first and then request headers similar to Authorization: Bearer

are added to authenticate the interface when invoking the interface. There are three ways to achieve this in Swagger:

  1. Added to interface parameter description@ApiImplicitParamWhere the parameter type isParamType=header
  2. Add global interface parameters
  3. Add a security authentication context

6.1 Adding Interface Authentication Parameters

For the interface that requires authentication, use @apiIMPLicitParam. The parameter type is ParamType=header. The parameter description has been described before. As follows:

@ApiImplicitParam(name = "Authorization", value = "Token, format: Bearer & LTTOken>", required = false, dataType = "String",paramType = "header")
Copy the code

The disadvantage of this approach is that you need to add this parameter description for each interface, and the description is the same and repetitive.

6.2 Adding Global Interface Parameters

GlobalOperationParameters swagger configuration, the method can set the global parameters.

// Global header arguments
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("Authorization").description("The token token")
    .modelRef(new ModelRef("string"))
    .parameterType("header")
    .required(true).build();
pars.add(tokenPar.build());
docket.globalOperationParameters(pars);
Copy the code

This method has obvious disadvantages. Because global parameters are set, all interfaces need this parameter. If some interfaces do not need this parameter, special processing is required.

6.3 Adding a Security Authentication Context

Set the authentication mode and use the regular formula to filter the interfaces that need authentication, so that swagger interface provides a unified authentication interface. As follows:

docket.securitySchemes(securitySchemes()) .securityContexts(securityContexts()); ./ / to omit
private List<ApiKey> securitySchemes(a) {
		return Lists.newArrayList(
				new ApiKey("Authorization"."Authorization"."header"));
	}
private List<SecurityContext> securityContexts(a) {
    return Lists.newArrayList(
        SecurityContext.builder()
        .securityReferences(defaultAuth())
        // Regular filtering, where all interfaces that do not start with login require authentication
        .forPaths(PathSelectors.regex("^ (? ! login).*$"))
        .build()
    );
}
List<SecurityReference> defaultAuth(a) {
    AuthorizationScope authorizationScope = new AuthorizationScope("global"."Authentication Permission");
    return Lists.newArrayList(
        new SecurityReference("Authorization".new AuthorizationScope[]{authorizationScope}));
}
Copy the code

After setting, enter login, and the effect is as follows:

7. To summarize

This paper describes in detail the use and enterprise practice of Swagger, mainly introduces the principle of Swagger, how to use Springboot and Swagger to create interface documents, parameterize swagger configuration and packet filtering, detailed use of Swagger annotations, interface authentication methods, etc. Sample code used in this article has put github:https://github.com/mianshenglee/my-example, interested students can pull code, combined with the example study together.

The resources

  • Swagger website: https://swagger.io/

  • Springfox website: http://springfox.github.io/springfox/

  • Using Swagger documents in Spring Boot projects: https://www.ibm.com/developerworks/cn/java/j-using-swagger-in-a-spring-boot-project/index.html

  • SpringBoot2 configuration swagger2 and unified join authentication parameters: https://www.jianshu.com/p/7a24d202b395

  • An article with you understand Swagger and SpringBoot integration: https://mp.weixin.qq.com/s/1KuBFfMugJ4pf3cSEFfXfw

The articles

  • After consulting more than ten learning resources, I summarized this AI learning path
  • Java Application Monitoring (8)- Arthas Diagnostics tool
  • Java Application Monitoring (7)- Online dynamic diagnostic artifact BTrace
  • Java Application Monitoring (6)- Third-party memory analysis tool MAT
  • Mongo Synchronization – Spring Batch (8) is used by mongo read-write components

Follow my official account for more technical records: