SpringBoot e-Commerce project mall (35K + STAR) address: github.com/macrozheng/…

Abstract

Swagger as an API document generation tool, although the function is very complete, there are still some shortcomings. Knife4j fills in the gaps and gives Swagger more power. Today we’ll talk about how to use it.

Knife4j profile

Knife4j is an enhanced UI implementation of Springfox-Swagger that provides Java developers with a concise, powerful interface documentation experience when using Swagger. Knife4j follows exactly the way springfox-Swagger is used, with enhancements, so if you’ve used Swagger, you can seamlessly switch to Knife4J.

Quick start

Now let’s show you how to use Knife4J in SpringBoot in just two steps!

  • Add knife4J dependencies to POM.xml;
<! - integration Knife4j -- -- >
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.4</version>
</dependency>
Copy the code
  • Add an @enableKnife4J annotation to Swagger2Config that enables KNIfe4J enhancements;
/** * Swagger2API file configuration */
@Configuration
@EnableSwagger2
@EnableKnife4j
public class Swagger2Config {}Copy the code
  • Run our SpringBoot application, access to the API documentation address to view: http://localhost:8088/doc.html

Functional features

Let’s compare Swagger and see how knife4J differs from it!

JSON enhancement

Usually, Swagger is always used, but Swagger’s JSON support is not very good, JSON cannot be folded, too long to read, there is no parameter verification function when passing JSON format parameters. These pain points are all addressed with Knife4J.

  • Return result set support folding, easy to view;

  • Request parameters have JSON verification function.

Login authentication

Knife4j also supports adding tokens in the header for login authentication.

  • First of all inAuthorizeThe Token returned by login is added to the function.

  • Then in each interface you can see that the Token information has been carried in the request header.

Offline files

Knife4j supports exporting offline documents to others easily and supports Markdown format.

  • Direct selectionDocument Management -> Offline DocumentsFunction, and then selectDownload the MarkdownCan;

  • Let’s take a look at the exported Offline documentation of Markdown, which is quite detailed.

Global parameters

Knife4j supports temporary global parameters and supports two types: Query (form) and Header (request header).

  • For example, if we want to add a parameter appType to all request headers to distinguish between Android and ios calls, we can add it to the global parameter.

  • When the interface is called again, it containsappTypeThis request header.

Ignore parameter attributes

Sometimes the interface we create and modify will use the same object as the request parameter, but we do not need the ID when we create, and we need the ID when we modify, so we can ignore the ID attribute.

  • For example, the create item interface here, id, item quantity, item comment quantity can all be generated in the background without passing, can be provided by KNIfe4J@ApiOperationSupportAnnotations to ignore these attributes;
/** * Controller * Created by macro on 2019/4/19. */
@Api(tags = "PmsBrandController", description = "Product Brand Management")
@Controller
@RequestMapping("/brand")
public class PmsBrandController {
    @Autowired
    private PmsBrandService brandService;

    private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);

    @ApiOperation("Add brand")
    @ApiOperationSupport(ignoreParameters = {"id"."productCount"."productCommentCount"})
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
        CommonResult commonResult;
        int count = brandService.createBrand(pmsBrand);
        if (count == 1) {
            commonResult = CommonResult.success(pmsBrand);
            LOGGER.debug("createBrand success:{}", pmsBrand);
        } else {
            commonResult = CommonResult.failed("Operation failed");
            LOGGER.debug("createBrand failed:{}", pmsBrand);
        }
        returncommonResult; }}Copy the code
  • View the interface document at this time, found that these three attributes have disappeared, so that the front-end development view interface document will not feel that you define useless parameters, is not very good function!

The resources

Official document: doc.xiaominfo.com/guide/

Project source code address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, attention to the public number the first time access.