前后端分离
前后端分离:
- 后端:后端控制层(Controller),服务层(Service),数据访问层(Dao)
- 前端:前端控制器,视图层
- 前后端通过API接口来交互
当前后端人员在交互时,无法做到"及时协商,尽早解决",时,我们需要指定一些方案
解决方案:
- 首先指定一个计划,实时更新最新API,降低集成的风险
- 早些年:指定word文档;
- 前后端分离:
前端测试后端接口:postman
后端提供接口,需要实时更新最新的消息及改动
Swagger简介
- 目前最流行的API框架
- RestFul API:文档在线自动生成工具===》代码写完,文档实时更新
- 直接运行,可以在线测试API接口
在项目中使用Swagger需要Springbox;
- ui
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- Swagger2
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
maven官网:添加链接描述
SpringBoot集成Swagger
- 需要导入依赖
- 配置Swagger===>Config·
- 生成一个配置类(SwaggerConfig)
@Configuration //用于定义配置类,
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
@Configuration //用于定义配置类,被注解的类内部包含一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContextg或AnnotationConfigWebApplicationContext类进行扫描,构建bean,初始化Spring容器
我们可以通过 http://localhost:8080/swagger-ui.html 访问Swagger
配置Swagger
Swagger有一个Bean实例Docket
Api
这里实例的是ApiInfoBuilder,没有实例ApiInfo,所以可以不使用无参构造
Swagger配置扫描接口
Docket.getSelect()
@Bean
public Docket SwaggerConfigTest(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//basePackage("com.zydn.project127.Controller"):扫描指定包名下的接口
//any():扫描所有接口
//none():不扫描所有接口
//withClassAnnotation(RestController.class):扫描类上的注解,类上有该注解的就扫描该类的所有接口
//withMethodAnnotation(GetMapping.class):扫描方法上的注解,方法上有该注解的就扫描该接口
.apis(RequestHandlerSelectors.basePackage("com.zydn.project127.Controller"))
//PathSelectors.any():过滤所有接口,相当于加了where子句
//PathSelectors.ant("/com.cdzy/**"):在com.cdzy包下扫描所有接口
.paths(PathSelectors.any())
.build();
}
我们过滤了所有接口paths(PathSelectors.any()),且扫描指定包名的接口,所有Swagger有两个接口信息,因为Controller只有该两个接口
配置是否Swagger
.enable(false):关闭了Swagger
可以看到我们关闭了Swagger,所有访问不到Swagger的基本信息