This is the 22nd day of my participation in the August Wen Challenge.More challenges in August

Web interface development in the debugging phase is the most troublesome parameter debugging, the front-end need to consult the back-end. Sometimes the back end itself is not very well understood. This will cause you to debug the interface once and look at the code once. Swagger takes care of our docking problems

Springboot access swagger

  • Springboot introduces Swagger by importing jar packages and configuring Swagger to start. And with Swagger’s annotation use can achieve automatic document generation. Let’s look at the effect first

Environment to prepare

  • The code is still based on the Spring repository. Branch for feature / 0004 / springboot – swagger

  • Swagger. Version = 2.9.2


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

Copy the code

configuration


@Configuration
@EnableSwagger2
public class SwaggerConfig2 {
    @Bean
    public Docket createRestApi(a) {

        // Add request parameters, we pass token as request header parameter back end
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameters = new ArrayList<Parameter>();
        parameterBuilder.name("token").description("Token")
                .modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        parameters.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build().apiInfo(new ApiInfoBuilder()
                        .title("Back-end Service Description")
                        .description("SpringBoot integrate Swagger, details......")
                        .version("1.0")
                        .contact(new Contact("zxhtom"."zxhtom.blog.csdn.net"."[email protected]"))
                        .license("The Apache License")
                        .licenseUrl("http://zxhtom.gitee.io")
                        .build())
                .useDefaultResponseMessages(false)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .globalOperationParameters(parameters);
    }


    private List<ApiKey> securitySchemes(a) {
        List<ApiKey> apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("Authorization"."token"."header"));
        return apiKeyList;
    }

    private List<SecurityContext> securityContexts(a) {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^ (? ! auth).*$"))
                        .build());
        return securityContexts;
    }

    List<SecurityReference> defaultAuth(a) {
        AuthorizationScope authorizationScope = new AuthorizationScope("global"."accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        returnsecurityReferences; }}Copy the code

Add headers


securitySchemes(securitySchemes())
securityContexts(securityContexts())

Copy the code
  • The configurations on both ends are global token Settings. The Swagger-UI interface displays a lock logo in the upper right corner

Interface to use

Annotations using

annotations function
@Api() Used on the requested class. The request class representing this class is used for document annotations
@ApiOperation() Used methodically. Description of an HTTP request, input parameter description
@ApiModel() A description of the requesting entity
@ApiModelProperty You can also set default values for attributes within entities
@ApiImpliciParams() Inside the method used for the request is the ApiImpliciParam array
@ApiImpliciParam() Represents a single request parameter. You can set parameters in the form to be set separately
@ApiParam() The individual setting of parameters in the request method is similar to ApiImpliciParam
@ApiResponses() Set instructions on the request method according to the response code
@ApiResponse Description of a single response code
@ApiIgnore() The request was ignored
  • Specific use can view the source code. The source code is given above.

Custom swaggerUI

  • Here is the loading order of Spring resources.

src/main/resources/META-INF/resources src/main/resources/static src/main/resources/public

  • These three priorities decrease in order. Spring first looks for resources under SRC /main/resources/ meta-INF /resources. So this is also our strategy for customizing swaggerUI. We just need to redraw the swaggerUI page under Meta-INF. This is just an idea. Not concrete (lazy)