springboot(05)整合 swagger2自动生成API文档

Swagger是一种开源的API文档工具,它可以自动生成RESTful API文档,让开发者可以更容易地理解和使用API。使用Swagger可以提高开发效率,减少文档编写的工作量,并降低开发者之间的沟通成本。Swagger可以生成各种不同类型的文档,包括HTML、PDF、JSON和XML等。将Swagger与Spring Boot结合使用可以更加方便地生成API文档,并提供实时的API测试功能。使用Swagger可以提高API的可读性和可维护性,使API更易于开发人员和用户使用。

swagger2自动生成API文档 (一)

1.首先,在pom.xml文件中添加以下依赖:

<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>

2.然后在写一个配置类

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    
    
    private static ApiInfo DEFAULT = null;
    @Bean
    public Docket docket(){
    
    
        return new Docket(DocumentationType.SWAGGER_2);
    }
}

访问网页

http://localhost:8082/swagger-ui.html#/

swagger2自动生成API文档 (二)

在Spring Boot应用中整合Swagger,可以通过以下步骤来配置application.yml文件:

  1. 首先,在pom.xml文件中添加以下Swagger依赖:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>{Swagger版本号}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>{Swagger版本号}</version>
</dependency>
  1. 接着,在application.yml文件中添加以下内容:
# Swagger配置
swagger:
  # API文档基础信息
  info:
    title: ${
    
    spring.application.name}
    description: Spring Boot集成Swagger自动生成API文档
    version: 1.0
    contact:
      name: Your Name
      url: <https://www.example.com>
      email: [email protected]
  # API文档扫描的包路径
  base-package: com.buba.controller
  # API文档生成的URL路径
  path-mapping: /

其中,swagger.info指定了API文档的基本信息,swagger.base-package指定了API文档扫描的包路径,swagger.path-mapping指定了API文档生成的URL路径。

  1. 在Spring Boot应用的启动类上添加@EnableSwagger2注解:
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
    }
}

通过以上步骤,即可在Spring Boot应用中使用Swagger自动生成API文档。

猜你喜欢

转载自blog.csdn.net/Bilal_0/article/details/129937689