怎样搞定SpringBoot 整合 Swagger2

发布时间:2021-12-02 16:13:05 作者:柒染
来源:亿速云 阅读:190
# 怎样搞定SpringBoot 整合 Swagger2

## 前言

在当今前后端分离的开发模式下,API文档的维护成为开发过程中的重要环节。Swagger2作为一套强大的API文档生成工具,能够自动生成美观且交互式的接口文档。本文将详细介绍如何在SpringBoot项目中整合Swagger2,让你的API文档管理事半功倍。

## 一、环境准备

### 1. 创建SpringBoot项目
通过Spring Initializr或IDE工具创建基础项目,确保包含以下依赖:
```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 添加Swagger2依赖

在pom.xml中添加核心依赖:

<!-- Swagger2核心依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- Swagger UI界面依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

二、基础配置

1. 创建配置类

新建SwaggerConfig.java配置类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SpringBoot整合Swagger2")
                .description("API接口文档")
                .version("1.0")
                .build();
    }
}

2. 配置项说明

三、接口文档注解

1. 常用注解说明

注解 作用 示例
@Api 标注在Controller类上 @Api(tags = "用户管理")
@ApiOperation 标注在方法上 @ApiOperation("用户登录")
@ApiParam 标注在参数上 @ApiParam("用户名") String username
@ApiModel 标注在实体类上 @ApiModel("用户实体")
@ApiModelProperty 标注在实体字段上 @ApiModelProperty("用户ID")

2. 完整Controller示例

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理接口")
public class UserController {
    
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    public User getUser(@PathVariable @ApiParam("用户ID") Long id) {
        // 业务逻辑
    }
    
    @PostMapping
    @ApiOperation("新增用户")
    public void addUser(@RequestBody @Valid User user) {
        // 业务逻辑
    }
}

四、访问与测试

  1. 启动SpringBoot应用
  2. 访问Swagger UI界面:http://localhost:8080/swagger-ui.html
  3. 在界面中可以:
    • 查看所有API接口
    • 在线测试接口
    • 查看请求/响应模型

五、常见问题解决

1. 404无法访问

2. 接口文档不显示

3. 生产环境禁用

建议通过Profile控制:

@Profile({"dev", "test"})
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    // 配置内容
}

结语

通过本文的步骤,你应该已经成功实现了SpringBoot与Swagger2的整合。Swagger不仅能自动生成API文档,还能提供便捷的接口测试功能,大大提高了开发效率。建议在开发过程中保持文档的及时更新,让前后端协作更加顺畅。 “`

(注:实际字数约750字,可根据需要增减示例代码部分调整篇幅)

推荐阅读:
  1. SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
  2. SpringBoot整合Swagger2实例方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot swagger

上一篇:ADO.NET类库的对象有哪些

下一篇:tk.Mybatis插入数据获取Id怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》