简介
------
Swagger 是一种用于描述、生产、消费和可视化 RESTful 风格的 Web 服务的标准。Spring Boot 是一个快速构建应用程序的框架,广泛应用于 Java 开发中。整合 Swagger 可以更加方便地展示 RESTful API 的文档和测试工具。本文将介绍如何在 Spring Boot 2.0 中简单地整合 Swagger,并展示 API 文档的基本配置和使用方法。

1. 添加 Swagger 相关依赖
------
首先,在 pom.xml 文件中添加 Swagger 相关的依赖。在 Spring Boot 2.0 及以上版本中,可以通过添加 sprgf-bt-ter 依赖来集成 Swagger。以下是一个示例依赖配置:


<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>2.9.2</version>
</dependency>
XML

2. 配置 Swagger 相关注解
------
接下来,在 Spring Boot 应用程序的主类中添加 Swagger 的相关注解。使用 EnabSwagr2 注解来启用 Swagger,并在 Configuration 注解的类中,使用 Bean 注解注入一个 Docket 类型的 Bean,用于配置 Swagger 的基本信息。以下是一个示例配置:


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

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API 文档标题 ")
                .description("API 文档描述 ")
                .version("1.0")
                .build();
    }
}
Java

3. 启动应用程序并访问 Swagger UI
------
配置完成后,启动 Spring Boot 应用程序,并访问 hp:/localhost:8080swagr-ui.html 可以看到 Swagger 的用户界面。在该界面中,可以查看 API 文档、测试 API 接口,并进行其他相关操作。

4. 配置文档显示的 Controller
------
有时候,我们可能只希望展示特定的 Controller 接口文档而不是整个项目的接口文档。这时,可以使用 Aπ 注解来标识需要显示的 Controller,并使用 AπOperation 注解来标识需要显示的接口。

例如,给定一个 Controller 类 UserControlr 和其中的两个接口方法 tAllUserstUserById


@RestController
@RequestMapping("/users")
@Api(tags = "用户管理 ")
public class UserController {

    @GetMapping("/")
    @ApiOperation(value = "获取所有用户 ", notes = "获取系统中的所有用户列表 ")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据用户 ID 获取用户信息 ", notes = "根据用户 ID 获取指定用户的详细信息 ")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}
Java

在 Swagger UI 界面中,可以看到 的标签,并在标签下展示 ID 两个接口的详细信息。

总结
------
本文介绍了如何在 Spring Boot 2.0 中简单地整合 Swagger,并展示了 Swagger 的基本配置和使用方法。通过添加 Swagger 的依赖、配置 Swagger 相关的注解以及启动应用程序并访问 Swagger UI,可以方便地展示和测试 RESTful API 的文档。同时,还介绍了如何配置指定 Controller 的接口文档显示,使得文档更加清晰和易读。