Home >Java >javaTutorial >How to implement API annotation and document generation based on Spring Boot
Spring Boot, as one of the most popular Java frameworks at present, has the advantages of rapid development, high integration, and easy testing. During the development process, we often need to write API documents to facilitate front-end and back-end collaboration and future project maintenance.
However, manually writing API documentation is very time-consuming and error-prone, so this article will introduce how to use Spring Boot's own annotations and some tools to automatically generate API comments and documentation.
1. Swagger
Swagger is currently one of the most popular Java API annotation and document generation tools. It can automatically generate API documentation by scanning annotations in Spring projects, and can also provide an interactive API exploration interface.
To use Swagger, you need to add the following dependencies to your Spring Boot project:
<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>
Then, add the annotation @EnableSwagger2 in the Spring Boot startup class, as shown below:
@SpringBootApplication @EnableSwagger2 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
Then, you can add annotations provided by Swagger to your Controller's methods to generate API documents.
For example, the following is a simple UserController:
@RestController @RequestMapping("/user") public class UserController { @ApiOperation(value = "获取用户列表", notes = "获取所有用户的列表") @GetMapping("/list") public List<User> getUserList() { return userService.getUserList(); } @ApiOperation(value = "创建用户", notes = "根据User对象创建用户") @PostMapping("/") public String postUser(@RequestBody User user) { userService.saveUser(user); return "success"; } @ApiOperation(value = "获取用户详情", notes = "根据id获取用户的详情") @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.getUserById(id); } @ApiOperation(value = "更新用户信息", notes = "根据id更新用户的信息") @PutMapping("/{id}") public String putUser(@PathVariable Long id, @RequestBody User user) { User u = userService.getUserById(id); if (u == null) { return "用户不存在"; } userService.updateUser(user); return "success"; } @ApiOperation(value = "删除用户", notes = "根据id删除用户") @DeleteMapping("/{id}") public String deleteUser(@PathVariable Long id) { User u = userService.getUserById(id); if (u == null) { return "用户不存在"; } userService.deleteUser(id); return "success"; } }
By adding the annotation @ApiOperation and other related annotations, Swagger will automatically generate API documentation and provide an interactive API exploration interface.
You can view your API documentation by visiting http://localhost:8080/swagger-ui.html.
2. Spring REST Docs
Spring REST Docs is another Java API annotation and documentation generation tool that allows you to write API documentation using AsciiDoc, Markdown or HTML format.
Using Spring REST Docs, you need to add the following dependencies to your Spring Boot project:
<dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-mockmvc</artifactId> <version>2.0.2.RELEASE</version> </dependency>
Next, add the annotation @WebMvcTest in your test class, as follows:
@RunWith(SpringRunner.class) @WebMvcTest(UserController.class) public class UserControllerTests { @Autowired private MockMvc mockMvc; @Test public void getUserList() throws Exception { this.mockMvc.perform(get("/user/list")) .andExpect(status().isOk()) .andDo(document("getUserList", responseFields( fieldWithPath("[].id").description("用户ID"), fieldWithPath("[].name").description("用户名"), fieldWithPath("[].age").description("用户年龄") ))); } @Test public void postUser() throws Exception { User user = new User(); user.setName("Tom"); user.setAge(20); ObjectMapper mapper = new ObjectMapper(); String userJson = mapper.writeValueAsString(user); this.mockMvc.perform(post("/user/") .contentType(MediaType.APPLICATION_JSON) .content(userJson)) .andExpect(status().isOk()) .andDo(document("postUser", requestFields( fieldWithPath("name").description("用户名"), fieldWithPath("age").description("用户年龄") ))); } @Test public void getUser() throws Exception { this.mockMvc.perform(get("/user/{id}", 1)) .andExpect(status().isOk()) .andDo(document("getUser", pathParameters( parameterWithName("id").description("用户ID") ), responseFields( fieldWithPath("id").description("用户ID"), fieldWithPath("name").description("用户名"), fieldWithPath("age").description("用户年龄") ))); } @Test public void putUser() throws Exception { User user = new User(); user.setName("Tom"); user.setAge(20); ObjectMapper mapper = new ObjectMapper(); String userJson = mapper.writeValueAsString(user); this.mockMvc.perform(put("/user/{id}", 1) .contentType(MediaType.APPLICATION_JSON) .content(userJson)) .andExpect(status().isOk()) .andDo(document("putUser", pathParameters( parameterWithName("id").description("用户ID") ), requestFields( fieldWithPath("name").description("用户名"), fieldWithPath("age").description("用户年龄") ))); } @Test public void deleteUser() throws Exception { this.mockMvc.perform(delete("/user/{id}", 1)) .andExpect(status().isOk()) .andDo(document("deleteUser", pathParameters( parameterWithName("id").description("用户ID") ))); } }
By adding corresponding annotations and field descriptions, Spring REST Docs will automatically generate API documentation and save it in the /target/generated-snippets directory, which you can convert into the final documentation format.
3. Summary
This article introduces two methods to implement API annotation and document generation based on Spring Boot. Swagger provides a convenient and easy-to-use method, and the generated documents are relatively intuitive and easy to understand, making it suitable for small projects or rapid development. Spring REST Docs provides a more flexible and customizable approach, which can be applied to more complex projects and scenarios that require higher quality API documentation.
No matter which method you choose, it is essential that the API documentation is correct, standardized and clear. It not only facilitates front-end and back-end collaboration, but also helps long-term maintenance of your project.
The above is the detailed content of How to implement API annotation and document generation based on Spring Boot. For more information, please follow other related articles on the PHP Chinese website!