Springboot集成Swagger
1. Swagger简介1.1 前后端分离发展历史
后端时代:
前段只用管静态页面;html==>后端。模版引擎JSP=>后端是助理
前后端分离时代:
后端:后端控制层,服务层,数据访问层次【后端团队】
前段:前端控制层,视图层【前段团队】。 伪造后端数据json已经存在了,不需要后端,前段工程依旧可以跑起来。
那么问题来了?
前后端如何交互?===》API
前后端相对独立,松耦合
前后端甚至可以部署在不同的服务器上
生产一个问题:
前后端集成联调,前后端人员无法做到“及时协商,尽早解决”,导致问题集中爆发。
首先指定一个schema,实时更新最新的api,降低集成风险。
早些年,制定word文档
前后端分离:前端测试后端接口:post; 后端提供接口,需要实时更新最新的消息以及改动
1.2 Swagger产生
Swagger:
[*]号称世界上最流行的API框架
[*]Restful Api文档在线自动生成工具=>API文档与API定义同步更新
[*]直接运行,在线测试API接口
[*]支持多种语言
[*]官网地址:https://swagger.io/
2. SpringBoot集成Swagger
2.1初步集成swagger
<ol>新建一个Springboot-web项目,编写一个hello工程
导入相关依赖
1
2 <dependency>
3 <groupId>io.springfox</groupId>
4 springfox-swagger2</artifactId>
5 <version>2.9.2</version>
6 </dependency>
7
8 <dependency>
9 <groupId>io.springfox</groupId>
10 springfox-swagger-ui</artifactId>
11 <version>2.9.2</version>
12 </dependency>配置Swagger1 @Configuration //配置类
2 @EnableSwagger2// 开启Swagger2的自动配置
3 public class SwaggerConfig {
4 }
测试运行 http://localhost:8080/swagger-ui.html ;包含四部分:Swagger信息 接口信息 实体信息 组
配置Swagger扫描接口 1 package com.study.cloud.config; 23 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.context.annotation.Profile; 6 import org.springframework.core.env.Environment; 7 import org.springframework.core.env.Profiles; 8 import springfox.documentation.RequestHandler; 9 import springfox.documentation.builders.PathSelectors;10 import springfox.documentation.builders.RequestHandlerSelectors;11 import springfox.documentation.service.ApiInfo;12 import springfox.documentation.service.Contact;13 import springfox.documentation.spi.DocumentationType;14 import springfox.documentation.spring.web.plugins.Docket;15 import springfox.documentation.swagger2.annotations.EnableSwagger2;16 17 import java.util.ArrayList;18 19 @Configuration //配置类20 @EnableSwagger2// 开启Swagger2的自动配置21 public class SwaggerConfig {22 @Bean23 public Docket docket(Environment environment){24 Profiles profiles = Profiles.of("dev","test");25 boolean flag = environment.acceptsProfiles(profiles);26 returnnew Docket(DocumentationType.SWAGGER_2)27 .apiInfo(apiInfo())28 .groupName("Cloud2022组")//分组名称不能有空格29 .enable(flag)//通过enable()方法配置是否启用swagger,如果是false,swagger将不能在浏览器中访问了30 .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口31 /*32 any() // 扫描所有,项目中的所有接口都会被扫描到33 none() // 不扫描接口34 withMethodAnnotation(final Class
页:
[1]