栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot Swagger2的使用 -- 自用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Boot Swagger2的使用 -- 自用

导入swagger
    // swagger文档相关库
    implementation 'io.springfox:springfox-swagger2:2.9.2'
    implementation 'io.springfox:springfox-swagger-ui:2.9.2'
    implementation "com.github.xiaoymin:swagger-bootstrap-ui:1.9.6"
    implementation 'com.github.xiaoymin:knife4j-spring-boot-starter:2.0.4'
SwaggerConfig.java
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Profile({"dev", "test"})
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(documentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 加了ApiOperation注解的类,才会生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 指定包下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .paths(PathSelectors.any())
                .build()
//                .securitySchemes(security())
                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口文档")
                .description("接口文档")
                .termsOfServiceUrl("https://www.52itit.com/")
                .version("1.0.0")
                .build();
    }

    private List security() {
        return Lists.newArrayList(
                new ApiKey("token", "token", "header")
        );
    }

    private List securityContexts() {
        return Lists.newArrayList(
                SecurityContext.builder().securityReferences(defaultAuth())
                        //过滤要验证的路径
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build()
        );
    }

    //增加全局认证
    List defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List securityReferences = new ArrayList<>();
        // 由于 securitySchemes() 方法中 header 写入值为 token,所以此处为 token
        securityReferences.add(new SecurityReference("token", authorizationScopes));
        return securityReferences;
    }
}
查看Json文档路径
域名+/v2/api-docs
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/771098.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号