要使用 Spring Boot 的 YAML 方式和注解使用 Swagger,您需要执行以下步骤:

  1. 首先,确保您的项目中已经包含了以下依赖项:
<!-- Spring Boot Web 相关依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Swagger 相关依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  1. 在您的 Spring Boot 主类上添加@EnableSwagger2注解,以启用 Swagger:
@SpringBootApplication
@EnableSwagger2
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
  1. 配置 Swagger 的基本信息(例如 API 文档的标题、描述等):
swagger:
  # API 文档基本信息配置
  info:
    title: 'My API'
    description: 'Description of my API'
    version: '1.0.0'
  1. 在您的控制器类上添加 Swagger 注解,以描述 API 的参数、返回值等信息:
@RestController
@RequestMapping("/api")
@Api(tags = "API")
public class MyController {
    @GetMapping("/hello")
    @ApiOperation("Say hello")
    public String sayHello(@RequestParam("name") String name) {
        return "Hello, ' + name + '!";
    }
}
  1. 启动您的应用程序并访问http://localhost:8080/swagger-ui.html,您将看到自动生成的 API 文档。

注意:在使用 Swagger 时,请确保您的控制器类上使用了正确的注解。例如,如果您使用了@RestController注解,则需要在该类上添加@Api(tags = "API")注解,而不是@Api(tags = "RestController")注解。


原文地址: https://www.cveoy.top/t/topic/nPCP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录