您的位置:首页 > 游戏 > 游戏 > 广东东莞市_宁波公司核名网站_成都百度推广电话_如何建立网站平台

广东东莞市_宁波公司核名网站_成都百度推广电话_如何建立网站平台

2025/2/24 4:46:28 来源:https://blog.csdn.net/gdjnrc_com/article/details/145783643  浏览:    关键词:广东东莞市_宁波公司核名网站_成都百度推广电话_如何建立网站平台
广东东莞市_宁波公司核名网站_成都百度推广电话_如何建立网站平台

Springfox Swagger 是一个用于构建基于 Spring Boot 的 RESTful API 文档的开源工具。它通过使用注解来描述 API 端点,自动生成易于阅读和理解的 API 文档。Springfox 通过在运行时检查应用程序,基于 Spring 配置、类结构和各种编译时 Java 注释来推断 API 语义。

在 Java 项目中使用 Springfox 有以下好处:

  1. 自动生成 API 文档:Springfox 可以帮助我们自动生成描述 API 的 JSON 文件(Swagger 2.0规范),这使得 API 文档的编写变得非常容易和高效。
  2. 可视化 API 文档:Springfox 还提供了一个 Swagger UI,可以将 API 规范以交互式文档的形式展示出来,使得开发者和用户可以更加直观地理解和使用 API。
  3. 减少重复劳动:使用 Springfox 可以减少开发人员编写和维护 API 文档的工作量,从而提高开发效率。

需要注意的是,Springfox 3.x 版本已经移除了对 Guava 和其他第三方库的依赖,因此如果之前使用了 Guava predicates/functions,需要将其转换为 Java 8 函数接口。同时,在 SpringBoot 项目中整合 Springfox 通常需要用到两个依赖:springfox-swagger2 和 springfox-swagger-ui。

快速上手 springfox

安装依赖

如果是新项目,添加以下为 maven 依赖

<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>

Gradle 则添加这个

  implementation "io.springfox:springfox-boot-starter:<version>"

Swagger 配置入口


@SpringBootApplication
@EnableSwagger2 //支持 swagger 2.0 spec
@EnableOpenApi //支持 open api 3.0.3 spec
public class Application {public static void main(String[] args) {ApplicationContext ctx = SpringApplication.run(Application.class, args);}@Beanpublic PetController petController() {return new PetController();}

引入 swagger UI

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>3.0.0</version>
</dependency>

设置 Swagger UI 静态资源目录


@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}

试试修改 Controller

@RestController
public class CustomController {@RequestMapping(value = "/custom", method = RequestMethod.POST)public String custom() {return "custom";}
}

Entity 校验

@Entity
public class User {//...@NotNull(message = "First Name cannot be null")private String firstName;@Min(value = 15, message = "Age should not be less than 15")@Max(value = 65, message = "Age should not be greater than 65")private int age;
}

浏览器验证 Json 文件

访问 http://localhost:8080/api/v2/api-docs,如果配置没问题的话,就可以拿到 swagger spec 文件。

访问 http://localhost:8080/swagger-ui/ 看是否能够看到 Swagger UI。

Swagger UI

Swagger UI

示例代码

以下是一个基于 Springfox Swagger 的代码示例:

@RestController
@RequestMapping("/api/v1/users")
@Api(tags = "User Management", description = "Operations for managing users")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/{id}")@ApiOperation(value = "Get user by ID", notes = "Get the user information by user ID")@ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully retrieved user information"),@ApiResponse(code = 404, message = "User not found"),@ApiResponse(code = 500, message = "Internal server error")})public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {User user = userService.getUserById(id);if (user == null) {return ResponseEntity.notFound().build();}return ResponseEntity.ok(user);}@PostMapping@ApiOperation(value = "Create user", notes = "Create a new user with the given user information")@ApiResponses(value = {@ApiResponse(code = 201, message = "Successfully created user"),@ApiResponse(code = 400, message = "Invalid request body"),@ApiResponse(code = 500, message = "Internal server error")})public ResponseEntity<User> createUser(@RequestBody @Valid User user) {User newUser = userService.createUser(user);return ResponseEntity.created(URI.create("/api/v1/users/" + newUser.getId())).body(newUser);}@PutMapping("/{id}")@ApiOperation(value = "Update user", notes = "Update an existing user with the given user information")@ApiResponses(value = {@ApiResponse(code = 200, message = "Successfully updated user"),@ApiResponse(code = 400, message = "Invalid request body"),@ApiResponse(code = 404, message = "User not found"),@ApiResponse(code = 500, message = "Internal server error")})public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody @Valid User user) {User updatedUser = userService.updateUser(id, user);if (updatedUser == null) {return ResponseEntity.notFound().build();}return ResponseEntity.ok(updatedUser);}@DeleteMapping("/{id}")@ApiOperation(value = "Delete user", notes = "Delete an existing user by user ID")@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully deleted user"),@ApiResponse(code = 404, message = "User not found"),@ApiResponse(code = 500, message = "Internal server error")})public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {boolean deleted = userService.deleteUser(id);if (deleted) {return ResponseEntity.noContent().build();}return ResponseEntity.notFound().build();}
}

在上述示例代码中,使用了多个注解来描述 API 端点,例如:

  • @RestController:标识该类为一个 RESTful API 的控制器。
  • @RequestMapping:标识该控制器中所有 API 端点的基本路径。
  • @GetMapping@PostMapping@PutMapping@DeleteMapping:分别表示 GET、POST、PUT 和 DELETE 请求的 API 端点。
  • @Api:用于为该控制器中所有 API 端点添加一个描述性的标签和说明。
  • @ApiOperation:用于为单个 API 端点添加一个描述性的标签和说明。
  • @ApiResponses:用于为单个 API 端点添加一个或多个可能的响应消息。

除了上述注解之外,示例代码还包括了其他的注解,如 @PathVariable@RequestBody@Valid 等。这些注解用于描述 API 端点的输入参数和返回结果。

在添加了注解之后,开发人员可以使用 Springfox Swagger 来自动生成 API 文档。例如,通过访问 /v2/api-docs 端点,可以获取生成的 Swagger JSON 文件。另外,通过访问 /swagger-ui.html 端点,可以获取一个可视化的 Swagger UI 界面,用于查看和测试 API 端点。

好用的 API 开发者工具

Springfox Swagger 是一个功能强大的工具,但也有一些缺点:

  1. 学习成本高:使用 Springfox Swagger 需要掌握大量的注解和配置,这需要一定的学习成本。特别是对于初学者来说,可能需要花费更多的时间来了解和掌握 Springfox Swagger 的使用方法。
  2. 文档生成的细节有限制:虽然 Springfox Swagger 能够自动生成 API 文档,但是文档生成的细节受到限制,无法自动识别一些细节,例如 API 端点间的依赖关系、数据模型的细节等。这些需要开发者手动进行配置。
  3. API 文档维护需谨慎:API 文档的内容需要和代码一致,如果开发者没有及时更新 API 文档,就可能导致文档和实际代码不一致,增加维护的难度。
  4. 不支持自定义文档:尽管 Springfox Swagger 提供了多种自定义主题和样式的选项,但仍存在一些自定义文档的需求无法满足。例如,开发者可能需要根据特定的需求,生成自己定制的 API 文档,而这是不容易实现的。
  5. 增加应用程序复杂度:在将 Springfox Swagger 集成到应用程序中时,需要增加一些配置和注解,这可能会增加应用程序的复杂度。这也可能会增加代码的维护成本,特别是在大型项目中。

对于开发者,我们更推荐一体化 API 工具 Apifox:Apifox 是一个接口管理、开发、测试全流程集成工具,可以通过一套系统、一份数据解决多个系统之间的 API 数据同步问题。Apifox 提供的功能包括接口文档管理、接口调试、数据 Mock、接口测试等,可以帮助团队提高效率,降低沟通成本。 此外,Apifox 还有许多创新功能,如接口支持用例管理、接口支持分组管理、多人协作编辑等,都可以提高团队的开发效率。

立即体验 Apifox

一体化 API 工具 Apifox

同时 Apifox 还提供了基于 IDEA 的插件 Apifox Helper,在 IDEA 写好代码后,可以基于插件自动生成 API 文档,对于很多苦恼于如何从代码生成规范 API 文档的开发者来说,开箱即用更易用。

 IDEA 的插件 Apifox Helper

它不仅仅是一个数据打通的工具,还做了很多创新,来提升开发人员的效率。由于其功能全面、工作流逻辑清晰,支持多场景使用,以及对用户的上心程度,Apifox 受到高效能软件团队的喜爱。

好用的 API 开发者工具

与其他接口管理工具相比,Apifox 在产品本身的功能全面性、工作流逻辑清晰性以及多场景使用方面都表现出色。此外,Apifox 对用户的上心程度也很高,对用户提出的需求也会关注并且采纳。

立即体验 Apifox

Apifox 在产品本身的功能全面

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com