preface

Companies are now developing in a way that separates the front and back ends, and this project is a pure back end framework. To better connect the front and back ends, you need to document the API.

However, handwritten API documents have several pain points:

  • After function modification, update the document in time. It is easy to have function document mismatch
  • After the document is updated, users need to be notified in time, which is easy to cause delayed communication
  • The interface parameters and return result are not clear
  • You can’t test directly online, you need to use a tool such as Postman
  • There are too many interface documents to manage

Swagger2: That’s not a problem.

Then why can it be so arrogant, its effect is how, we come to the actual operation below.

The specific implementation

Adding Maven dependencies

<! -- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
Copy the code

Create a Swagger configuration

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket docket(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                // apis specify the scan conditions for the generated API
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                / / scan packages
                //.apis(RequestHandlerSelectors.basePackage("com.zhuqc.framework.controller"))
                // paths Specifies the path for generating the API
                .paths(PathSelectors.any())
                .build()
                // Document information
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo(a) {
        return new ApiInfoBuilder()
                .title("Building a back-end framework from scratch.")
                .description("API Interface Documentation")
                .termsOfServiceUrl("https://github.com/zhuqianchang/framework")
                .contact(new Contact("zhuqianchang"."".""))
                .version("0.0.1") .build(); }}Copy the code
  • @ EnableSwagger2 Swagger2
  • Apis are used to specify scan conditions
    • RequestHandlerSelectors. BasePackage (” com. Zhuqc. Framework. The controller “), and scanning specified package
    • RequestHandlerSelectors. WithClassAnnotation ((Api) class), scanning @ Api class
    • RequestHandlerSelectors. WithMethodAnnotation (ApiOperation. Class), scan @ ApiOperation labeling method
    • RequestHandlerSelectors. Any (), is always true
    • RequestHandlerSelectors. None (), is false
    • The default configuration is classes and methods without the @APIIgnore annotation
  • Paths specifies the path for generating the API
    • PathSelectors. Any (), always true
    • PathSelectors. None (), always false
    • PathSelectors. Regex (), regular expression matching
    • PathSelectors. Ant (), ant expression matches
  • ApiInfo is used to specify document information

Swagger use

@Api(description = "Hello services")
@RestController
public class HelloController {

    @ApiOperation(value = "Say hello", notes = "Greeting Details")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "Username", required = true)})@GetMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return String.format("Hello %s!", name); }}Copy the code

Common annotations

  • The @Api decorates the entire class and describes what the entire Controller does
  • The @apiOperation modifier describes the function of a method
  • @apiParam Decorates a parameter to describe its role
  • @apiIgnore: Ignores the current API
  • @apiIMPLICITParams describes multiple request parameters
  • @apiIMPLICITParam describes a request parameter
  • @APIModel If the argument is an object, it is annotated on the object’s class to describe the object
  • @APIModelProperty If the argument is an object, it is annotated on the properties of the object’s class to describe the properties of the object

Start the project

Preparatory work has been completed, start the project after the access to Swagger address: http://localhost:8080/swagger-ui.html

The test results are as follows:

At this point, Swagger2 is integrated. We should get into the habit of modifying the interface description at the same time as developing or modifying the interface. So when docking with the front end, just throw him a Swagger address.

Q&A

In actual operations, the following problems may occur:

This is because the @enablesWagger2 annotation was not added.

The source code

Github.com/zhuqianchan…

Review past

  • Build backend frameworks from scratch – keep updating