Using Swagger in the Spring Boot project

Keywords: Programming Java Google Apache REST

Project environment

Srping Boot Version

2.0.6.RELEASE

JDK Version

1.8

configuration file

Configure Swagger, using the Swagger.java file

Swagger.java

package com.xxx.xxx.xxx.config;

import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

/**
 * SwaggerConfig
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    //@Value("${server.servlet-path}")
    private String pathMapping;

    private ApiInfo initApiInfo() {
        ApiInfo apiInfo = new ApiInfo("Here's the big title",//Headline
                initContextInfo(),//A simple description
                "1.0.0",//Edition
                "Terms of Service",
                "Background development team",//author
                "The Apache License, Version 2.0",//Link display text
                "http://www.baidu.com "//website link
        );

        return apiInfo;
    }

    private String initContextInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append("REST API Design has its own unique skill to note in detail and is more architecturally capable than traditional API There are higher requirements.")
                .append("<br/>")
                .append("In this paper, through a detailed description and a series of examples, from the overall structure to local details, analysis and interpretation to improve ease of use and efficiency. REST API What problems should be noted in the design and how to solve them.");

        return sb.toString();
    }


    @Bean
    public Docket restfulApi() {

        List<ResponseMessage> responseMessageList = new ArrayList<>();

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Group Name")
//                .genericModelSubstitutes(DeferredResult.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                //.pathMapping // base, the interface will be stitched together with paths when finally called
                //.pathMapping("api/v1") // base, the interface will be stitched together with paths when finally called
                .select()
                //.paths(doFilteringRules())
      // Configure scanned interface package location.apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.xxx.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(Lists.newArrayList(apiKey()))
                .apiInfo(initApiInfo());
    }

    private ApiKey apiKey() {
        return new ApiKey("apikey", "Authentication", "header");
    }

    /**
     * SecurityScheme Subclass BasicAuth OAuth ApiKey
     * @return
     */
    private SecurityScheme securitySchemes(){
        // Bad support for basicAuth SwaggerBootstrapUI, use swagger native UI
        return new BasicAuth("basicAuth");
    }

    /**
     * Set filter rules
     * The filtering rules here support regular matching
     * @return
     */
    private Predicate<String> doFilteringRules() {
        return or(
                regex("/hello.*"),
                regex("/vehicles.*")
        );
    }
}

Some user-defined configuration information, package location and key information of the interface are configured here after Swagger starts.

The information that needs to be configured in this project to prevent it from being intercepted and inaccessible.

WebMvcConfig.java

package com.xxx.xxx.xxx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");

        //super.addResourceHandlers(registry);
    }

    @Bean
    public RequestContextListener requestContextListenerBean() {
        return new RequestContextListener();
    }
}

Configuration does not intercept "swagger-ui.html" to prevent Swagger from being inaccessible.

Next is the configuration of the Pom file:

Pom.xml

<!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        <!-- END Swagger -->

The github open source component is selected for implementation.

Controller interface layer

Controller needs to be defined to correspond to the above path, using the @Api annotation on the Controller class, using @ApiOperation on specific interface methods, and using the @ApiImplicitParams annotation with additional explanations of parameters.

UserController.java


package com.xxx.xxx.xxx.controller;

import com.bjbde.admin.common.annotation.Log;
import com.bjbde.admin.common.controller.BaseController;
import com.bjbde.admin.common.domain.QueryRequest;
import com.bjbde.admin.common.exception.FebsException;
import com.bjbde.admin.common.utils.MD5Util;
import com.bjbde.admin.system.domain.User;
import com.bjbde.admin.system.domain.UserConfig;
import com.bjbde.admin.system.service.UserConfigService;
import com.bjbde.admin.system.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;

@Api(value = "API - UserController", tags = "Run Management System-security management-user management")
@Slf4j
@Validated
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    private String message;

    @Autowired
    private UserService userService;
    @Autowired
    private UserConfigService userConfigService;

    @ApiOperation(value = "Check that candidate user names are available (unique)", notes = "Check that candidate user names are available (unique).", response = String.class, authorizations = {@Authorization(value="apikey")})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "Candidate User Name", required = true, dataType = "string", paramType = "path")
    })
    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
        return this.userService.findByName(username) == null;
    }

}

Entity Class

Entity classes need to be annotated @Api To annotate the entity class; the @ApiModelProperty property needs to be annotated on attributes

User.java

package com.xxx.xxx.xxx.domain;

import com.bjbde.admin.common.converter.TimeConverter;
import com.bjbde.admin.common.domain.RegexpConstant;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wuwenze.poi.annotation.Excel;
import com.wuwenze.poi.annotation.ExcelField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;

@Data
@ApiModel("user")
@TableName("user")
@Excel("User Information Table")
public class User implements Serializable {

    private static final long serialVersionUID = -4852732617765810959L;

    @ApiModelProperty(value = "User Number")
    @TableId(value = "USER_ID", type = IdType.AUTO)
    private Long userId;

    @ApiModelProperty(value = "User name")
    @Size(min = 4, max = 20, message = "{range}")
    @ExcelField(value = "User name")
    private String username;

    @ApiModelProperty(value = "Password")
    private String password;

    @ApiModelProperty(value = "Full name")
    @NotBlank(message = "{required}")
    @ExcelField(value = "Full name")
    private String fullName;

    @ApiModelProperty(value = "Department number")
    private Long deptId;

    @ApiModelProperty(value = "department")
    @ExcelField(value = "department")
    private transient String deptName;

}


At this point, the Swagger annotation configuration section is almost complete.

Access Address

http://{IP}:{Port}/swagger-ui.html

Get the document page as follows

Posted by squiggerz on Thu, 07 Nov 2019 12:33:30 -0800