当前位置:   article > 正文

springdoc-openapi使用_springdoc.openapi.title

springdoc.openapi.title

一、引入pom

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.5.12</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

二、新增配置类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 globalHeaderCustomizer() {
        //遍历所有操作(即接口)
        return (Operation operation, HandlerMethod handlerMethod) -> {
            //设置全局请求头参数
            setHeader(operation);
            return operation;
        };
    }
    private void setHeader(Operation operation){
        Parameter clusterIdParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name("clusterId")
                .description("clusterId")
                .required(false);

        Parameter tokenParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name("sessionid")
                .description("sessionid")
                .required(true);

        Parameter userIdParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new IntegerSchema())
                .name("userid")
                .description("userid")
                .required(true);

        Parameter useraccountParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name("useraccount")
                .description("useraccount")
                .required(true);

        Parameter userroleParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name("userrole")
                .description("userrole")
                .required(false);

        Parameter projectnameParam = new Parameter()
                .in(ParameterIn.HEADER.toString())
                .schema(new StringSchema())
                .name("projectname")
                .description("projectname")
                .required(false);


        operation.addParametersItem(clusterIdParam);
        operation.addParametersItem(projectnameParam);
        operation.addParametersItem(tokenParam);
        operation.addParametersItem(useraccountParam);
        operation.addParametersItem(userIdParam);
        operation.addParametersItem(userroleParam);

    }

    @Bean
    public OpenApiCustomiser globalResponseCustomizer() {
        return openApi -> {
            openApi.getPaths().forEach((path, pathItem) -> {
                pathItem.readOperations().forEach(operation -> {

                    ApiResponses responses = operation.getResponses();
                    if(responses == null){
                        responses = new ApiResponses();
                    }

                    // 添加全局响应
                    addGlobalResponse(responses);
                    // 将合并后的响应设置回操作
                    operation.setResponses(responses);
                });
            });
        };
    }

    private void addGlobalResponse(ApiResponses responses){
        responses.addApiResponse("0",new ApiResponse().description("成功"));
        responses.addApiResponse("1",new ApiResponse().description("失败"));

        for (ServerStatus item : ServerStatus.values()) {
            responses.addApiResponse(String.valueOf(item.getErrorCode()),new ApiResponse().description(item.getMessage()));
        }
    }


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112

全局请求头参数设置参考文章:
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库路径");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

五、配置文件新增内容

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

六、验证

启动项目后访问地址http://<serviceIp>:<port>/swagger-ui/index.html
在这里插入图片描述
展示接口页面表示成功

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/616026
推荐阅读
相关标签
  

闽ICP备14008679号