6, spring boot tutorial -- integrating swagger

Keywords: Spring Java Docker JSON

spring boot tutorial -- integrating swagger

1, About swagger

Swagger is a standardized and complete framework for generating, describing, invoking, and visualizing RESTful style Web services. The overall goal is to have the client and file system update at the same speed as the server. File methods, parameters, and models are tightly integrated into the server-side code, allowing the API to always keep in sync.

  1. Swagger Codegen: through Codegen, the description files can be generated into html format and cwiki format interface documents, as well as multi language server and client code. Support local generation through jar package, docker, node and other methods. It can also be generated online in later Swagger Editor.

  2. Swagger UI: provides a visual UI page presentation description file. The caller, test and project manager of the interface can view the relevant interface and make some simple interface requests in this page. The project supports online import of description files and local deployment of UI projects.

  3. Swagger Editor: similar to the editor of markendown editor, the editor of Swagger description file supports the update effect of real-time preview description file. Online editor and local deployment editor are also provided.

  4. Swagger Inspector: it's similar to postman. It's an online version of postman that can test the interface. More information will be returned than interface request in Swagger UI, and the actual request parameters and other data you requested will also be saved.

  5. Swagger Hub: integrates the functions of all the above projects. You can upload your description file to Swagger Hub in terms of project and version. In Swagger Hub, you can complete all the work of the above project. You need to register an account, which is divided into free version and charge version.

  6. Spring fox swagger: Based on the swagger specification, spring can automatically generate description files in JSON format from project code based on spring MVC and Spring Boot projects. It is not provided by swagger's official website. Here is a list for explanation, which is convenient for later use.

2. How to use swagger

1. Introduce the jar package of swagger

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

2. Write swagger configuration class

Create a new Swagger2Config class under package com.core.deformation.config. The code is as follows:

package com.core.deformation.config;

import io.swagger.models.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger2 Configuration class
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        Contact contact = new Contact();
        contact.setEmail("pin621@163.com");
        contact.setName("Api Interface specification");
        contact.setUrl("localhost:8090");
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.core.deformation.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("Deformation monitoring")
                        .description("Deformation monitoring Api Explain")
                        .version("1.0")
                        .contact("Watch the destiny")
                        .license("The Apache License")
                        .licenseUrl("http://localhost:8090")
                        .build());
    }
}

3. Code in controller

Common notes:

  • @Api() for classes;
    Indicates that this class is a resource of swagger
  • @ApiOperation() is used for methods;
    Represents an http requested operation
  • @ApiParam() is used for method, parameter and field description;
    Indicates the metadata added to the parameter (description or required, etc.)
  • @ApiModel() for classes
    Represents the description of a class, which is used to receive parameters with entity class
  • @ApiModelProperty() for method, field
    Indicates a description or data operation change to the model property
  • @ApiIgnore() for class, method, method parameter
    Indicates that this method or class is ignored
  • @ApiImplicitParam() for methods
    Represents a separate request parameter
  • @ApiImplicitParams() is used for methods and contains multiple @ apiimplicitparams
package com.core.deformation.controller;

import com.core.deformation.domain.Company;
import com.core.deformation.service.CompanyService;
import com.core.deformation.util.UUIDUtil;
import com.core.deformation.util.result.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/api/company")
@Slf4j
@Api(tags = "Relevant interface of unit management")
public class CompanyController {

    @Autowired
    private CompanyService companyService;

    @GetMapping("/{id}")
    @ApiOperation("Get company entity according to primary key")
    @ApiImplicitParam(name = "id", value = "Unit primary key", required = true, dataType = "String", paramType = "path")
    public Company get(@PathVariable String id) {
        log.info("Get. . {}. . Method execution", id);
        return companyService.findById(id);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("Delete company entity according to primary key")
    @ApiImplicitParam(name = "id", value = "Unit primary key", required = true, dataType = "String", paramType = "path")
    public String delete(@PathVariable String id) {
        Company company = companyService.findById(id);
        return "Delete successful";
    }

    @PostMapping
    @ApiOperation("Add unit entity")
    public Company save(@RequestBody Company company) {
        company.setCompanyId(UUIDUtil.getUUIDDispose());
        company.setCreateTime(new Date());
        company.setModifyTime(new Date());
        return companyService.save(company);
    }

    @PutMapping("/{id}")
    @ApiOperation("Update unit entity based on primary key")
    @ApiImplicitParam(name = "id", value = "Unit primary key", required = true, dataType = "String", paramType = "path")
    public Company update(@PathVariable("id") String id, @RequestBody Company company) {
        return companyService.save(company);
    }
}

3, Operation effect

Published 6 original articles, praised 0 and visited 108
Private letter follow

Posted by geetakhurana on Wed, 19 Feb 2020 02:04:24 -0800