Spring Boot 3 整合 SpringDoc OpenAPI 生成接口文档
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Tag(name = "Example", description = "Example endpoints for SpringDoc OpenAPI integration")
@RestController
public class ExampleController {
@Operation(summary = "Get greeting", tags = "Example")
@ApiResponse(responseCode = "200", description = "Greeting message", content = @Content(mediaType = "text/plain"))
@GetMapping("/greeting")
public ResponseEntity<String> greeting(
@Parameter(description = "Name of the user", required = false)
@RequestParam(name = "name", defaultValue = "World") String name) {
return new ResponseEntity<>("Hello, " + name + "!", HttpStatus.OK);
}
}
这段代码演示了如何在Spring Boot 3项目中使用SpringDoc OpenAPI来创建一个简单的API端点,并生成相应的接口文档。它使用了@Tag
注解来定义一个端点的分类和描述,@Operation
注解描述了操作的摘要和标签,@ApiResponse
注解定义了响应的HTTP状态码和描述,@GetMapping
定义了请求的URL和响应的媒体类型。这个例子简单明了,展示了如何将OpenAPI注解应用到Spring Boot应用中。
评论已关闭