| Swagger是什么?Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。 Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。 简单来说Swagger就是一个用于测试后端接口的框架 Swagger 的优势支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。
 Swagger的使用1、在SpringBoot项目中引入依赖         <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
 注:springfox它的前身是swagger-springmvc 3、写出Swagger的配置类 @Configuration
public class SwaggerConfiguration {
    public Docket createRestApi(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("springboot整合swagger3的接口文档")
                .description("描述图书管理的接口文档")
                .contact(new Contact("springboot","http://www.diyt.com","dyit@dyit.com"))
                .version("1.0")
                .build();
    }
}
 3、在启动类中加入@EnableOpenApi注解开启Swagger @SpringBootApplication
@Slf4j
@EnableOpenApi
public class Main {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Main.class);
        springApplication.run(args);
        log.debug("成功");
    }
}
 4、在接口上加上注解@Tag @Operation @Tag(name = "出版社模块")
@RestController
@RequestMapping("/api/publisher")
@Slf4j
public class PublisherController {
    @Autowired
    private IPublisherService iPublisherService;
    @Operation(summary = "获取所有出版社信息")
    @GetMapping("/findAll")
    public HttpResp findAll(){
        List<Publisher> list = iPublisherService.findAll();
        log.debug(list.toString());
        return new HttpResp(1000,"查询成功",new Date(),list);
    }
}
 在dto返回对象上也加入注解@Schema @Schema(description = "DTO对象")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResp {
    @Schema(description = "后台返回状态码")
    private int code;
    @Schema(description = "后台返回信息")
    private String msg;
    @Schema(description = "后台返回数据")
    private Date date;
    @Schema(description = "后台返回时间")
    private Object results;
}
 测试结果接口查看地址可以通过**服务地址 +swagger-ui/**来访问 
 Swagger的优点: 使前端和后端更加解耦,前后端的对接通常是API形式,而后端开发人员在开发的过程中,提供的API和描述文档却是难以同步的,往往是开发代码完成了,但文档描述并不及时,甚至会忘记这一环节,导致前端调用API时经常发生错误,因此,springfox应运而生,它将前后端有效分离,并保证了API与文档的实时同步;使用springfox生成的接口文档直观可视,也帮助后端开发人员脱离了写接口文档的痛苦,及避免不厌其烦的解说各个接口需要的参数和返回结果;,因此,springfox应运而生,它将前后端有效分离,并保证了API与文档的实时同步;
使用springfox生成的接口文档直观可视,也帮助后端开发人员脱离了写接口文档的痛苦,及避免不厌其烦的解说各个接口需要的参数和返回结果;springfox支持在线测试,可实时检查参数和返回值。
 |