本节视频
手写文档存在的问题
文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
接口返回结果不明确
不能直接在线测试接口,通常需要使用工具,比如:Postman
接口文档太多,不好管理
使用 Swagger 解决问题
Swagger 也就是为了解决这个问题,当然也不能说 Swagger 就一定是完美的,当然也有缺点,最明显的就是代码植入性比较强。
Maven
增加 Swagger2 所需依赖,pom.xml 配置如下:
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
配置 Swagger2
注意:RequestHandlerSelectors.basePackage("com.funtl.myshop.service") 为 Controller 包路径,不然生成的文档扫描不到接口
创建一个名为 Swagger2Configuration 的 Java 配置类,代码如下:
package com.funtl.myshop.commons.service.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.funtl.myshop.service"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("MyShop API 文档")
.description("MyShop API 网关接口,http://www.funtl.com")
.termsOfServiceUrl("http://www.funtl.com")
.version("1.0.0")
.build();
}
}
启用 Swagger2
Application 中加上注解 @EnableSwagger2 表示开启 Swagger
package com.funtl.myshop.service.reg;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.a