找回密码
 申请加入
查看: 467|回复: 0

EnableOpenApi具体应用案例?

[复制链接]

62

主题

78

回帖

157

积分

书童

积分
157
发表于 2023-8-11 12:46:40 | 显示全部楼层 |阅读模式
@EnableOpenApi是Springdoc开源库中的注解,用于启用OpenAPI规范和自动生成API文档。下面是@EnableOpenApi的具体应用案例:

假设我们正在使用Spring Boot和Spring MVC构建一个RESTful API,并希望为该API生成相应的文档。

1. 首先,确保已将Springdoc库添加到项目的依赖项中。

2. 在主应用程序的入口类上添加`@EnableOpenApi`注解,以启用OpenAPI规范和API文档的自动生成。

   ```java
   import org.springdoc.core.SpringDocConfigProperties;
   import org.springframework.boot.SpringApplication;
   import org.springframework.boot.autoconfigure.SpringBootApplication;
   import org.springframework.context.annotation.Bean;
   import springfox.documentation.swagger2.annotations.EnableSwagger2;

   @SpringBootApplication
   @EnableOpenApi // 添加这个注解来启用OpenAPI规范
   public class YourApplication {
       public static void main(String[] args) {
           SpringApplication.run(YourApplication.class, args);
       }

       @Bean
       public SpringDocConfigProperties springDocConfigProperties() {
           return new SpringDocConfigProperties();
       }
   }
   ```

3. 编写一个控制器类,并使用Spring MVC的注解配置API的路径、请求方法和参数等信息。

   ```java
   import org.springframework.http.ResponseEntity;
   import org.springframework.web.bind.annotation.GetMapping;
   import org.springframework.web.bind.annotation.PathVariable;
   import org.springframework.web.bind.annotation.RequestMapping;
   import org.springframework.web.bind.annotation.RestController;

   @RestController
   @RequestMapping("/api")
   public class YourController {

       @GetMapping("/users/{id}")
       public ResponseEntity getUserById(@PathVariable Long id) {
           // 处理获取用户信息的逻辑
       }

       // 其他API方法...
   }
   ```

4. 启动应用程序,并访问`http://localhost:8080/swagger-ui.html`,您将看到自动生成的API文档页面。该页面将显示您的API的详细信息,包括路径、请求方法、参数和响应等。

通过在主应用程序类上添加@EnableOpenApi注解,可以轻松地启用OpenAPI规范和自动生成API文档功能,在开发过程中帮助团队成员快速了解和使用API,提高开发效率和代码质量。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 申请加入

本版积分规则

手机版| 赣榆百姓网 ( 苏ICP备11090745号|苏公网安备 32072102010002号 )

GMT+8, 2024-5-2 15:29 Powered by 网站建设 X3.5