swagger3.0

於意蕴
2023-12-01

一、添加maven依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

二、自定义配置

添加maven依赖后自带默认配置,默认开启swagger,默认访问地址http://localhost:8080/swagger-ui/index.html
这里我们通过java类进行自定义配置

package com.dirk.config;

import io.swagger.v3.oas.annotations.Operation;
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 java.util.Collections;
import java.util.List;

/**
 * @author Dirk
 */
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                .groupName("music")
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API 文档")
                .description("Project Api document")
                .version("API V1.0")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        return Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"));
    }

    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(SecurityContext.builder()
                .securityReferences(Collections.singletonList(SecurityReference.builder()
                        .reference("Authorization")
                        .scopes(new AuthorizationScope[]{new AuthorizationScope("global", "用户token")})
                        .build()))
                .build());
    }
}

三、 正式环境禁用swagger

springfox:
  documentation:
    enabled: false

四、常用注解

  • @Api(tags = {"这里填标签"}): swagger3 的标签为@Tag,但是实际使用中未生效,此处使用兼容的swagger2的注解,用于标记controller类的作用
  • @Operation(summary = "接口描述"): 接口注解,用于标记接口作用,代替swagger2中的@ApiOperation
 类似资料:

相关阅读

相关文章

相关问答