SpringBoot2 如何集成OpenAPI

在Spring Boot 2中集成OpenAPI(以前称为Swagger)以生成和维护RESTful API文档,最简单且推荐的方法是使用 springdoc-openapi 库。以下是详细的步骤:

步骤 1:添加依赖

对于Maven项目,在pom.xml文件中添加以下依赖:

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

步骤 2:配置应用属性(可选)

application.propertiesapplication.yml文件中设置一些属性来自定义OpenAPI的行为。例如:

# application.yml
springdoc:
  api-docs:
    path: /v3/api-docs
  swagger-ui:
    path: /swagger-ui.html

步骤 3:启动应用并访问

启动Spring Boot应用程序后,可以通过以下URL访问生成的API文档:

  • OpenAPI JSON/YAML: http://localhost:8080/v3/api-docs
  • Swagger UI: http://localhost:8080/swagger-ui.html

步骤 4:定制API文档(可选)

可以通过注解来描述API,比如使用@Operation, @ApiResponse, @Parameter等来自定义API文档中的信息。例如:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api")
@Tag(name = "My Custom API", description = "Operations for my custom API")
public class MyController {

    @GetMapping("/example")
    @Operation(summary = "Get an example resource", description = "Returns a simple example object.")
    @ApiResponse(responseCode = "200", description = "Successful operation")
    public ResponseEntity<MyExampleDTO> getExample() {
        // Implementation here...
        return new ResponseEntity<>(new MyExampleDTO(), HttpStatus.OK);
    }
}

提示

  • 如果使用了Spring Security,请确保配置适当的权限,以便能够访问Swagger UI和OpenAPI端点。
  • 可以通过设置springdoc.packagesToScan属性来限制扫描哪些包下的API接口。
  • 可以使用springdoc.group-configs来分组API。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值