Swagger:Springboot配置swagger

step1: Install dependent packages (choose one of the two)

<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.1.RELEASE</version>
</dependency>

Or add another dependency. The following dependencies need to be added.

<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>

 

step2: swagger configuration

Configure the information required by swagger in application.yml

swagger:
  enabled: true
  base-package: 'com.example.demo.controller'
  title: 'spring-boot-swagger-demo'
  description: '基于Swagger构建的SpringBoot RESTApi 文档'
  version: '1.0'
  contact:
    name: 'Jcsim'
    url: 'https://blog.csdn.net/weixin_38676276'
    email: '[email protected]'

 Create Swagger configuration class

package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Jcsim
 * @Date: 2020/10/24 15:30
 * @Description:
 */
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${swagger.enabled}")
    private boolean SwaggerSwitch;
    @Value("${swagger.base-package}")
    private String basePackage;
    @Value("${swagger.title}")
    private String title;
    @Value("${swagger.description}")
    private String description;
    @Value("${swagger.version}")
    private String version;
    @Value("${swagger.contact.name}")
    private String name;
    @Value("${swagger.contact.url}")
    private String url;
    @Value("${swagger.contact.email}")
    private String email;
    @Bean
    public Docket createRestApi() {
        log.info("======================== 当前环境是否开启Swagger:" + SwaggerSwitch + " ========================");
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                //配置是否启用Swagger,如果是false,在浏览器将无法访问,默认是true
                .enable(SwaggerSwitch)
                //apiInfo: 添加api详情信息,参数为ApiInfo类型的参数,这个参数包含了第二部分的所有信息比如标题、描述、版本之类的,开发中一般都会自定义这些信息
                .apiInfo(apiInfo())
                .select()
                //apis: 添加过滤条件,
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
//        Contact contact = new Contact("Jcsim", "http://www.Jcsim.cn", "[email protected]");
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(name, url, email))
                .version(version)
                .build();
    }

}

 

step3: Add annotations to the controller method

package com.example.demo.controller;

import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Jcsim
 * @Date: 2020/10/19 11:32
 * @Description:
 */
//@RestController
@Api(tags = "测试")
@RestController
@RequestMapping("/sys")
public class HelloController {
    @ApiOperation("测试swagger")
//@ApiImplicitParams:多个请求参数
    @ApiImplicitParams(
            value = {
                    @ApiImplicitParam(name = "key", value = "参数1", required = true, dataType = "String", defaultValue = "测试"),
                    @ApiImplicitParam(name = "key3", value = "参数2", required = true, dataTypeClass = java.lang.Integer.class, defaultValue = "1")
            }
    )
    @GetMapping("/hello")
    public Object sayHello(String key, Integer key3){
        Map<String,Object> maps = new HashMap<>();
        maps.put("key",key);
        maps.put("key3",key3);
        return maps;
    }

    @GetMapping("/test")
    public String hello(){
        return "test";
    }

    @GetMapping("/test2")
    public String hello2(){
        return "test222222222";
    }


    @GetMapping("/test25")
    public String hello25(){
        return "test22222222255555555555555555555555";
    }

}

step4: Start the project, visit http://localhost:8080/swagger-ui.html

 


Separate the front and back ends, adding the token request header

step1: Add the request header in the swagger configuration class

(Complete configuration class)

package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Jcsim
 * @Date: 2020/10/24 15:30
 * @Description:
 */
@Slf4j
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Value("${swagger.enabled}")
    private boolean SwaggerSwitch;
    @Value("${swagger.base-package}")
    private String basePackage;
    @Value("${swagger.title}")
    private String title;
    @Value("${swagger.description}")
    private String description;
    @Value("${swagger.version}")
    private String version;
    @Value("${swagger.contact.name}")
    private String name;
    @Value("${swagger.contact.url}")
    private String url;
    @Value("${swagger.contact.email}")
    private String email;
    @Bean
    public Docket createRestApi() {
        log.info("======================== 当前环境是否开启Swagger:" + SwaggerSwitch + " ========================");
        return new Docket(DocumentationType.SWAGGER_2)
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                //配置是否启用Swagger,如果是false,在浏览器将无法访问,默认是true
                .enable(SwaggerSwitch)
                //apiInfo: 添加api详情信息,参数为ApiInfo类型的参数,这个参数包含了第二部分的所有信息比如标题、描述、版本之类的,开发中一般都会自定义这些信息
                .apiInfo(apiInfo())
                .select()
                //apis: 添加过滤条件,
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
//        Contact contact = new Contact("Jcsim", "http://www.Jcsim.cn", "[email protected]");
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact(name, url, email))
                .version(version)
                .build();
    }

    /**
     * swagger加入全局Authorization header 将在ui界面右上角新增token输入界面
     * @return
     */
    private List<ApiKey> securitySchemes() {
        ApiKey apiKey = new ApiKey("Authorization", "token", "header");
        ArrayList arrayList = new ArrayList();
        arrayList.add(apiKey);
        return arrayList;
    }

    /**
     * 在Swagger2的securityContexts中通过正则表达式,设置需要使用参数的接口(或者说,是去除掉不需要使用参数的接口),
     * 如下列代码所示,通过PathSelectors.regex("^(?!auth).*$"),
     * 所有包含"auth"的接口不需要使用securitySchemes。即不需要使用上文中设置的名为“Authorization”,
     * type为“header”的参数。
     *
     */
    private List<SecurityContext> securityContexts() {
        SecurityContext build = SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.any())
                .build();
        ArrayList arrayList = new ArrayList();
        arrayList.add(build);
        return arrayList;
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        SecurityReference authorization = new SecurityReference("Authorization", authorizationScopes);
        ArrayList arrayList = new ArrayList<>();
        arrayList.add(authorization);
        return arrayList;
    }
}

step2: Direction page  http://localhost:8080/swagger-ui.html 

Authorize will be added at this time

step3: Click "Authorize" and enter the token value "aaa" in "value"

step4: Test the interface, you can see that the header is successfully added to the token

 



 

Swagger common annotations

Swagger interface can be generated by adding Swagger annotations to the Java class. Commonly used Swagger annotations are as follows: 

@Api: Decorate the entire class and describe the role of Controller 

@ApiOperation: describe a method of a class, or an interface @ApiParam: description of a single parameter 

@ApiModel: Use objects to receive parameters 

@ApiModelProperty: When receiving parameters with an object, describe a field of the object @ApiResponse: One of the descriptions in the HTTP response 

@ApiResponses: The overall description of the HTTP response

@ApiIgnore: Use this annotation to ignore this API

@ApiError: Information returned when an error occurs 

@ApiImplicitParam: a request parameter 

@ApiImplicitParams: Multiple request parameters

@ApiImplicitParam attributes:

Guess you like

Origin blog.csdn.net/weixin_38676276/article/details/109260952