【学习笔记】Swagger-01:SpringBoot集成Swagger


基本介绍

1.前后端分离

  • 后端:后端控制层,服务层,数据访问层

  • 前端:前端控制层,视图层

  • 前后端交互:===>API接口

优点:前后端相对独立,低耦合,可部署在不同服务器

缺点:前后端联调问题,无法”即时协商,尽早解决!“

解决方案:

  • 首先指定schema计划,实时更新API,降低集成风险
  • 指定word计划文档;
  • 前后端分离:前端测试后端接口(postman);后端提供接口,实时更新消息及改动

2.Swagger

官方地址:Swagger

  • RestFul Api文档在线自动生成工具===>Api文档和API定义同步更新
  • 直接运行,可在线测试API接口
  • 支持多种语言:Java、Php等

在项目使用swagger时需要引入springbox;

  • swagger2
  • swagger-ui

3.SpringBoot集成Swagger

3.1项目文件结构

image-20220303214401392

3.2项目配置步骤

1.新建SpringBoot-Web项目



    org.springframework.boot
    spring-boot-starter-web
    2.6.4

2.导入Swagger依赖(最新版本



    io.springfox
    springfox-swagger2
    3.0.0



    io.springfox
    springfox-swagger-ui
    3.0.0



    com.github.xiaoymin
    swagger-bootstrap-ui
    1.9.6


3.编写一个HelloController测试代码

@RestController
public class HelloController {
    @GetMapping("hello")
    public String hello(){
        return "hello";
    }
}

4.配置Swagger==>SwaggerConfig

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        /*规定扫描哪些包来生成接口文档*/
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.whut.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("DMP接口文档")
                .description("DMP接口文档")
                .contact(new Contact("叶小知","http:localhost:8080/doc.html","**********@qq.com"))
                .version("1.0")
                .build();
    }
}

5.配置application.yml

注意,这一步对于Spring2.6.x极其重要,不配置的话会运行失败,原因

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

当配置文件是application.properties时,配置文件为

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

3.3项目运行结果

image-20220303220845473