您的位置:首页 > 娱乐 > 八卦 > Spring Boot配置Springdoc

Spring Boot配置Springdoc

2025/2/26 0:42:49 来源:https://blog.csdn.net/qq_37759895/article/details/139957131  浏览:    关键词:Spring Boot配置Springdoc

刚刚开通了一个公众号,会分享一些技术博客和自己觉得比较好的项目,同时会更新一些自己使用的工具和图书资料,后面会整理一些面试资料进行分享,觉得有兴趣的可以关注一下。
在这里插入图片描述

问题描述

之前文章有提到Spring Boot切换到Springdoc,使用的是注解配置。但是每个API是有规范的,最近检查的时候,需要统一定义异常返回。这个时候注解就显得没那么有用了。需要改为编程式的,统一配置。


解决方案:

直接上代码:

@Configuration
public class SpringDocConfiguration {@Value("${spring.profiles.active:prod}")private String profile;@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("PROJECT - " + profile).version("1.0-SNAPSHOT").description("API Resources & Documentation").contact(new Contact().name("leeffy").email("leeffy@qq.com"))).addSecurityItem(new SecurityRequirement().addList("NewRiskAuthorize")).components(new Components().addSecuritySchemes("NewRiskAuthorize",new SecurityScheme().description("JWT认证").in(SecurityScheme.In.HEADER).type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));}
//    @Bean
//    public OpenApiCustomiser globalResponseStatusCustomizer() {
//        return openApi -> {
//            openApi.getComponents().getSchemas().forEach((key, schema) -> schema.additionalProperties(false));
//            openApi.getPaths().values().forEach(pathItem -> pathItem.readOperations().forEach(operation -> {
//                ApiResponses apiResponses = operation.getResponses();
//                apiResponses.addApiResponse("401", createApiResponse("Unauthorized"));
//                apiResponses.addApiResponse("403", createApiResponse("Unauthorized"));
//                apiResponses.addApiResponse("406", createApiResponse("Could not find acceptable representation"));
//                apiResponses.addApiResponse("429", createApiResponse("Request too much"));
//            }));
//        };
//    }//    private ApiResponse createApiResponse(String message) {
//        return new ApiResponse().description(message).content(new Content().addMediaType("text/plain",
//                new MediaType().schema(new Schema().$schema("string").pattern(".*").minLength(1).maxLength(50))));
//    }
}

注释的部分是统一定义返回响应码的地方。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com