search
HomeJavajavaTutorialHow 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.