掌握Swagger2,Spring MVC轻松实现API文档自动生成

日期:

最佳答案

在当今的软件开辟中,API文档的编写跟保护是一个至关重要的环节。精良的API文档可能极大年夜地晋升开辟效力跟用户休会。Swagger2是一个富强的API文档跟测试东西,可能轻松地与Spring MVC框架结合利用,实现API文档的主动生成。本文将具体介绍怎样控制Swagger2,并利用它来轻松实现Spring MVC项目标API文档主动生成。

一、Swagger2简介

Swagger2是一个基于OpenAPI标准的东西,可能用来生成、描述、测试跟可视化RESTful API。它供给了一个直不雅的界面来展示API的各个部分,包含端点、参数、恳求跟呼应等。

二、集成Swagger2到Spring MVC

要在Spring MVC项目中集成Swagger2,起首须要增加依附。以下是Maven依附设置:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Swagger2依附 -->
    <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>
</dependencies>

三、设置Swagger2

在Spring Boot项目标application.propertiesapplication.yml文件中增加以下设置:

# Swagger2设置
swagger:
  title: My API
  description: This is a sample API documentation
  version: 1.0.0
  termsOfServiceUrl: http://www.example.com/terms/
  contact:
    name: John Doe
    url: http://www.example.com/john
    email: john@example.com
  license: Apache 2.0
  licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.html

四、创建Swagger2设置类

创建一个设置类Swagger2Config,用于设置Swagger2的扫描包跟Docket:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.api"))
                .paths(PathSelectors.any())
                .build();
    }
}

五、创建API接口

在Spring MVC项目中创建一个API接口,比方:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Swagger!";
    }
}

六、启动项目并拜访Swagger UI

启动Spring Boot项目后,在浏览器中拜访http://localhost:8080/swagger-ui.html,即可看到主动生成的API文档。

七、总结

经由过程以上步调,我们曾经成功地将Swagger2集成到Spring MVC项目中,并实现了API文档的主动生成。利用Swagger2可能大年夜大年夜简化API文档的编写跟保护任务,进步开辟效力。在现实项目中,可能根据须要自定义Swagger2的设置跟文档内容,以满意差其余须要。