温馨提示×

温馨提示×

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

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

springBoot2.0如何简单整合swagger

发布时间:2021-09-29 17:52:27 来源:亿速云 阅读:158 作者:柒染 栏目:大数据
# SpringBoot2.0如何简单整合Swagger ## 前言 在当今前后端分离的开发模式下,API文档的编写与维护成为开发过程中不可或缺的环节。Swagger作为一套开源工具集,能够自动生成、描述、调用和可视化RESTful风格的Web服务,极大地提高了开发效率。本文将详细介绍如何在SpringBoot2.0项目中简单整合Swagger,实现API文档的自动化生成与管理。 ## 一、Swagger简介 ### 1.1 什么是Swagger Swagger是一套围绕OpenAPI规范构建的开源工具,主要包含以下组件: - **Swagger UI**:可视化API文档界面 - **Swagger Editor**:API设计编辑器 - **Swagger Codegen**:代码生成工具 - **Swagger Core**:Java注解库 ### 1.2 Swagger的优势 - **自动化文档**:代码变更后文档自动更新 - **交互式测试**:直接在文档界面调用API - **多语言支持**:支持多种编程语言 - **规范标准化**:基于OpenAPI规范 ## 二、环境准备 ### 2.1 创建SpringBoot项目 使用Spring Initializr创建基础项目,选择以下依赖: - Spring Web - Lombok(可选) ### 2.2 添加Swagger依赖 在`pom.xml`中添加Swagger2依赖: ```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> 

注意:SpringBoot2.6+版本需要额外配置路径匹配策略,推荐使用2.5.x版本

三、基础配置

3.1 创建Swagger配置类

@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("SpringBoot2.0整合Swagger") .description("API接口文档") .version("1.0") .contact(new Contact("开发者", "https://example.com", "contact@example.com")) .build(); } } 

3.2 配置项说明

  • @EnableSwagger2:启用Swagger2
  • Docket:Swagger的主要配置类
  • apiInfo:配置文档基本信息
  • apis():指定扫描的控制器包路径
  • paths():过滤URL路径

四、编写API接口

4.1 示例控制器

@RestController @RequestMapping("/api/user") @Api(tags = "用户管理接口") public class UserController { @GetMapping("/{id}") @ApiOperation(value = "获取用户详情", notes = "根据ID查询用户信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, paramType = "path") public ResponseEntity<User> getUser(@PathVariable Long id) { // 实现逻辑 } @PostMapping @ApiOperation(value = "创建用户", notes = "创建新用户") @ApiImplicitParam(name = "user", value = "用户实体", required = true, dataType = "User") public ResponseEntity createUser(@RequestBody User user) { // 实现逻辑 } } 

4.2 常用Swagger注解

注解 说明
@Api 修饰Controller类
@ApiOperation 描述API方法
@ApiParam 描述单个参数
@ApiModel 描述数据模型
@ApiModelProperty 描述模型属性

五、访问与测试

5.1 访问Swagger UI

启动应用后访问:

http://localhost:8080/swagger-ui.html 

5.2 界面功能

  • API列表展示
  • 模型定义查看
  • 接口在线测试
  • 文档下载(JSON格式)

六、高级配置

6.1 添加全局授权参数

@Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) // ...其他配置 .securitySchemes(Collections.singletonList( new ApiKey("Authorization", "Authorization", "header"))) .securityContexts(Collections.singletonList( SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("/.*")) .build())); } private List<SecurityReference> defaultAuth() { AuthorizationScope scope = new AuthorizationScope("global", "accessEverything"); return Collections.singletonList( new SecurityReference("Authorization", new AuthorizationScope[]{scope})); } 

6.2 分组配置

支持多个Docket实例实现API分组:

@Bean public Docket adminApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("管理接口") .select() .apis(RequestHandlerSelectors.withMethodAnnotation(AdminOnly.class)) .build(); } 

七、常见问题解决

7.1 404访问问题

检查是否配置了静态资源映射:

@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } } 

7.2 版本兼容问题

SpringBoot2.6+需要添加配置:

spring: mvc: pathmatch: matching-strategy: ant_path_matcher 

八、生产环境建议

  1. 访问限制:通过Spring Security限制Swagger UI的访问
  2. 版本控制:使用@Profile("dev")限定只在开发环境启用
  3. 文档导出:定期备份生成的JSON文档

结语

通过本文的介绍,我们实现了SpringBoot2.0与Swagger的简单整合。Swagger不仅提高了API文档的编写效率,还通过交互式测试功能提升了开发体验。在实际项目中,建议结合团队规范制定统一的注解使用标准,充分发挥Swagger的工具优势。

附录

参考资源

  1. Swagger官方文档
  2. SpringFox GitHub仓库
  3. OpenAPI规范

”`

该文章共计约2050字,采用Markdown格式编写,包含: 1. 完整的目录结构 2. 代码块与表格展示 3. 实际可操作的配置示例 4. 常见问题解决方案 5. 生产环境建议 6. 参考资源链接

可根据实际需求调整版本号或补充特定框架的整合细节。

向AI问一下细节

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

AI