java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springdoc openapi使用

springdoc openapi使用解决方案

作者:qq_44209563

SpringDoc注解的使用,它是基于OpenAPI 3和Swagger 3的现代化解决方案,相较于旧版的Swagger2即SpringFox,SpringDoc提供了更简洁、更直观的注解方式,这篇文章主要介绍了springdoc openapi使用,需要的朋友可以参考下

什么是SpringDoc

SpringDoc注解的使用,它是基于OpenAPI 3和Swagger 3的现代化解决方案,相较于旧版的Swagger2(SpringFox),SpringDoc提供了更简洁、更直观的注解方式。

一、引入pom

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.5.12</version>
        </dependency>

二、新增配置类OpenApiConfig

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI springShopOpenAPI() {
        OpenAPI openAPI = new OpenAPI()
                .info(new Info().title("制品中心 后台服务API接口文档")
                        .description("restful 风格接口")
                        .version("v0.0.1")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("SpringShop Wiki Documentation")
                        .url("https://springshop.wiki.github.org/docs"));
        return openAPI;
    }
    @Bean
    public OperationCustomizer customGlobalHeaders() {
        //设置全局请求头参数
        return (Operation operation, HandlerMethod handlerMethod) -> {
            Parameter tokenParam = new Parameter()
                    .in(ParameterIn.HEADER.toString())
                    .schema(new StringSchema())
                    .name("sessionid")
                    .description("sessionid")
                    .required(true);
            operation.addParametersItem(tokenParam);
            return operation;
        };
    }
}

全局请求头参数设置参考文章:

https://stackoverflow.com/questions/63671676/springdoc-openapi-ui-add-jwt-header-parameter-to-generated-swagger

三、Controller层示例

@Controller
@RequestMapping("/test")
@Tag(name = "测试接口")
@Validated
public class TestController {
    @Autowired
    private ArtifactService artifactService;
    @PostMapping("/v1/test")
    @Operation(summary  = "设置制品库权限")
    @NoPermission
    public Result<Void> addArtifactPermission(@Validated @RequestBody AssetAuthDataDTO assetAuthData, @RequestHeader(value = "adminaction", defaultValue = "false") boolean adminAction) {
        return null;
    }
    @Operation(summary = "添加", description = "添加描述",
            security = { @SecurityRequirement(name = "sessionid")},
            responses = {
                    @ApiResponse(description = "返回信息", content = @Content(mediaType = "application/json")),
                    @ApiResponse(responseCode = "400", description = "返回400时候错误的原因")
            }
    )
    @Parameters({
            @Parameter(name = "name", description = "名字", required = true),
            @Parameter(name = "typeId", description = "类型ID", required = true)
    })
    @PutMapping("add")
    @NoPermission
    public Result<Void> add(String name, String typeId) {
        return null;
    }
    /**
     * 查询generic制品库下所有文件列表
     *
     * @param quest 请求参数
     *
     * @return
     *
     * @author wangsb9
     * @data: 2023/4/6 14:54
     */
    @ApiOperation(value = "查询generic制品库下所有文件列表", httpMethod = "GET")
    @GetMapping("/v1/generic/item/list")
    @ResponseBody
    @RepoKeyPermission(permission = "read", param = "quest.repoKey")
    public Result<GenericItemListVO> getGenericItemList(GetGenericItemListQuest quest) {
        if (ArtifactTypes.GENERIC.equalsIgnoreCase(BusinessUtils.getArtifactTypeFromRepoKey(quest.getRepoKey()))) {
            GenericItemListVO vo = artifactService.geGenericItemList(quest);
            return Result.success("获取当前generic制品库包含的制品成功", vo);
        } else {
            return Result.failed("请求路径非generic库路径");
        }
    }
}

四、配置文件新增内容

application.yaml

springdoc:
  swagger-ui:
    # swagger-ui地址
    path: /swagger-ui/index.html
    enabled: true
    # 修复Failed to load remote configuration.
#    To configure, the path of a custom OpenAPI file . Will be ignored if urls is used
    url: /springdoc/api-docs
#  For custom path of the OpenAPI documentation in Json format.
  api-docs:
    path: /springdoc/api-docs
#  packages-to-scan: com.srdcloud.artifact.controller

五、验证

启动项目后访问地址http://<serviceIp>:<port>/swagger-ui/index.html

在这里插入图片描述

展示接口页面表示成功

到此这篇关于springdoc openapi使用的文章就介绍到这了,更多相关springdoc openapi使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文