刚刚开通了一个公众号,会分享一些技术博客和自己觉得比较好的项目,同时会更新一些自己使用的工具和图书资料,后面会整理一些面试资料进行分享,觉得有兴趣的可以关注一下。
问题描述
之前文章有提到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))));
// }
}
注释的部分是统一定义返回响应码的地方。