Detailed Swagger configuration-teach you how to play Swagger

This article introduces

This article mainly introduces the commonly used configuration of swagger, involving no token, partial token, global token, environmental restrictions, multi-person development and other modules, which basically meet all the uses in the project.

Basic configuration process (without token)

1. Introduce dependencies

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

2. Create a configuration class

@EnableSwagger2 Open configuration

@Configuration
@EnableSwagger2
public class MySwaggerConfig {
    
    
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * 多人开发可以设置多个Docket
     * @return
     */
    @Bean
    public Docket createRestApi(Environment environment) {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .groupName("小组管理系统")
                //false 则不能在浏览器访问,true为默认。
                .enable(true)
                .select()
                //配置扫描接口的方式,基于包去扫描
                .apis(RequestHandlerSelectors.basePackage("com.marchsoft.group.manager.system.controller"))
                //paths()过滤什么路径
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder().title("springboot利用swagger构建api文档")
                .description("基于小组管理的学生管理员系统")
                .termsOfServiceUrl("https://XXXX/XXXXX/group-manager/tree/develop/")
                .version("1.0")
                .build();
    }
}

3. Create an entity class

@ApiModel(value="学生DTO对象", description="返回所有S学生最基本的信息") Act on the model, introduce the current model

@ApiModelProperty(value = "id") Introduce an attribute of the current model

4. Create an interface

Introduce the basic information of the current interface and the author

@ApiOperation(value = "获取某一学生的详细信息",notes = " \n author:zhangh")

Introduce the parameters of the current interface

@ApiImplicitParams({@ApiImplicitParam(name = "id",value = "")})

	接口一:前端传递一个id
    @ApiOperation(value = "获取某一学生的详细信息",notes = " \n author:zhangh")
    @ApiImplicitParams({
    
    
            	@ApiImplicitParam(name = "id",value = "")
    })
    @PreAuthorize("hasAuthority('super_admin')")
    @GetMapping("/{id}")
    public Result getStudent(@PathVariable("id")    Long id) {
    
    
        StudentDTO student = studentService.getStudent(id);
        return Result.success(student);
    }
    
    接口二:  用于展示使用     前端传递的是一个对象
        @PutMapping("/update")
    public Result updateStudent(@RequestBody StudentDTO studentDTO){
    
    
        return null;
    }

5. Test and use (no token)

In the case of no token, we can configure the basic functions here.

Start the service and access the swagger path:

http://localhost:9898/swagger-ui.html

Place token

If a token is used in our system, it will undoubtedly need to be added during swagger testing. Next, we will introduce two ways to add tokens.

Local token

We need to manually add token information to each interface. trouble!

principle

Call the globalOperationParameters() method of Docket and pass in the basic configuration information of the token

Configuration and use:

This.apiInfo() method is in the basic configuration (there is source code in no token, so I won’t add it again here)

globalOperation()Details

    /***
     * @Author 
     * @Description  单一配置token
     * @Data 23:38 2021/1/29
     * @param
     * @return java.util.List<springfox.documentation.service.Parameter>
     */
    private List<Parameter> globalOperation(){
    
    
        //添加head参数配置start
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        //第一个token为传参的key,第二个token为swagger页面显示的值
        tokenPar.name("Authorization")
                .description("token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                //token前缀
                .defaultValue("Bearer ")
                .required(false).build();
        pars.add(tokenPar.build());
        return pars;
    }

Test use

Configuration control

Transfer object

see details

Global token

We just configured a local token. Although we can satisfy the usage, it is too troublesome. Next, let's configure the global token.

原理:

Use the configuration scheme provided by Docket and the two methods of configuring the context .

Steps for usage

Configure the above two methods in docket and pass in the parameters

Configuration information for the two methods:

    //设置基本的介绍信息
    private List<ApiKey> securitySchemes() {
    
    
        List<ApiKey> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }
    //过滤不需要进行验证的页面
    private List<SecurityContext> securityContexts() {
    
    
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        //带有auth的页面将不用提供token即可访问。
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }
    //全局的token配置
    private List<SecurityReference> defaultAuth() {
    
    
        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));
        return securityReferences;
    }

Test use

Extended use

1. Interface documents cannot be used in a formal environment

  • The system is usually divided into three environments, development environment (dev), test environment (test), and officially launched (pro).
  • Interface testing can only be performed in dev and test environments, and interface testing is strictly prohibited after the official launch.
  • Swagger also provides us with the corresponding, we can test in the dev and test environment, but not in the pro environment.

Configuration method

 //在开发或者测试服务器使用swagger,正式环境没有swagger
        //设置要显示的Swagger环境
        Profiles profiles = Profiles.of("dev","test");
        boolean flag = environment.acceptsProfiles(profiles);

effect

2. Interface documents under multi-person collaboration

In our normal development, the modules that everyone is responsible for may be different. If everyone is operating on a swagger page, it is quite confusing. At this time, we can use the grouping mechanism provided by swagger.

Principle analysis

The so-called grouping is to create multiple docket objects

Configuration steps

Create two Dockets

Test effect

swagger common annotations

Reference article

At the time of writing this article, I am still very knowledgeable, and I am grateful for the help of these big guys' blogs.

Crazy God said SpringBoot14: Integrated Swagger Ultimate Edition

https://mp.weixin.qq.com/s/0-c0MAgtyOeKx6qzmdUG0w

SpringBoot整合Springfox-Swagger2

https://www.cnblogs.com/yichunguo/p/12665857.html#1%E3%80%81swagger%E7%AE%80%E4%BB%8B

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/113405587