第 7 章 在您的 REST 控制器代码中添加 MicroProfile OpenAPI 注解


您可以在其他控制器代码中添加 MicroProfile OpenAPI 注解,以便为其余端点生成更详细的 OpenAPI 模式。

流程

  1. GreetingController 的类级别添加 @OpenApiDefinition 注释。在注解中包含示例中显示的数据:

    @OpenAPIDefinition(
        info = @Info(
            title="Greeting API",
            version = "1.0.1",
            contact = @Contact(
                name = "Greeting API Support",
                url = "http://exampleurl.com/contact",
                email = "techsupport@example.com"),
            license = @License(
                name = "Apache 2.0",
                url = "https://www.apache.org/licenses/LICENSE-2.0.html"))
    )
    Copy to Clipboard Toggle word wrap
  2. 使用 @Tag 注释标注端点定义。为每个端点提供名称和描述:

    @Tag(name = "Hello", description = "Just say hello")
    @GetMapping(produces=MediaType.TEXT_PLAIN_VALUE)
    public String hello() {
        return "hello";
    }
    
    @GetMapping(value = "/{name}", produces=MediaType.APPLICATION_JSON_VALUE)
    @Tag(name = "Hello to someone", description = "Just say hello to someone")
    public Greeting hello(@PathVariable(name = "name") String name) {
        return new Greeting("hello " + name);
    }
    Copy to Clipboard Toggle word wrap

    您在注解中提供的数据会出现在生成的 OpenAPI 模式中:

    openapi: 3.0.3
    info:
      title: Greeting API
      contact:
        name: Greeting API Support
        url: http://exampleurl.com/contact
        email: techsupport@example.com
      license:
        name: Apache 2.0
        url: https://www.apache.org/licenses/LICENSE-2.0.html
      version: 1.0.1
    tags:
    - name: Hello
        description: Just say hello
    - name: Hello to someone
        description: Just say hello to someone
    paths:
      /greeting:
        get:
          tags:
          - Hello
          responses:
            '200':
              description: OK
              content:
                text/plain:
                  schema:
                    type: string
      /greeting/{name}:
        get:
          tags:
          - Hello to someone
          parameters:
          - name: name
            in: path
            required: true
            schema:
              type: string
          responses:
            '200':
              description: OK
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/Greeting'
    
    components:
      schemas:
        Greeting:
          type: object
          properties:
            message:
              type: string
    Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat