How to automatically generate API documentation in SpringBoot?

In SpringBoot, interface documentation can be automatically generated using Swagger. Swagger is a tool for designing, building, and documenting APIs, making it easy to generate API documentation and providing an interactive UI interface for developers and users to intuitively understand the functionality and usage of the API.

Here are the steps to generate API documentation automatically using Swagger in SpringBoot.

  1. Add the Swagger dependency in the pom.xml file.
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  1. Add the @EnableSwagger2 annotation in the main class to enable Swagger.
@SpringBootApplication
@EnableSwagger2
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. Create a configuration class called SwaggerConfig to set up Swagger-related information.
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
            .paths(PathSelectors.any())
            .build();
    }
}
  1. Write a Controller class and use Swagger annotations on the methods.
@RestController
public class ExampleController {

    @ApiOperation("获取用户信息")
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        // code
    }
}
  1. You can view the generated API documentation by visiting http://localhost:8080/swagger-ui/.

By following the above steps, you can automatically generate interface documentation in a SpringBoot project and easily view the interface documentation through Swagger’s UI interface.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds