Springboot之整合Swagger3

依赖

        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-boot-starterartifactId>
            <version>3.0.0version>
        dependency>

配置

application.yaml

spring:
  # mvc这部分解决swagger3在新版本Springboot中无法展示的问题
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER

java实现配置类

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()// 自行修改为自己的接口路径,不配置扫描全部路径
                .apis(RequestHandlerSelectors.basePackage("com.itheima.controller"))
                .paths(PathSelectors.any()).build()//;
                .securitySchemes(securitySchemes())
                .securityContexts(Collections.singletonList(securityContext()));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("FH Admin Swagger3 RESTful API")     // 页面标题
                .description("fhadmin.org")                 // 描述
                .contact(new Contact("张三丰", "http://sanfen.com", "[email protected]"))
                .version("3.0")                             // 版本号
                .license("The apache license")
                .licenseUrl("http://www.apache.com.org")
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<>();
        //注意,这里应对应登录token鉴权对应的k-v
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    /*** 这里设置 swagger2 认证的安全上下文*/
    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(Collections.singletonList(new SecurityReference("Authorization", scopes()))).build();
    }

    /*** 这里是写允许认证的scope*/
    private AuthorizationScope[] scopes() {
        return new AuthorizationScope[]{new AuthorizationScope("web", "All scope is trusted!")};
    }

}

拦截配置

/**
 * 说明:Swagger 拦截配置
 * 作者:FH Admin
 * from fhadmin.org
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.
                addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/swagger-ui/")
                .setViewName("forward:/swagger-ui/index.html");
    }

}

你可能感兴趣的:(Java,spring,boot,后端,java)