swagger的作用是什么?
首先,你以后基本可以告别单元测试了;其次,你不用再写接口文档了,也不需要写完之后再去对文档进行维护了。swagger可以完全模拟http请求,入参出参和实际情况差别几乎为零。
既然这么方便那我们就集成到我们的SpringMVC项目中吧,很简单。
第一步:引入maven依赖
io.springfox
springfox-swagger2
2.6.1
io.springfox
springfox-swagger-ui
2.6.1
com.fasterxml.jackson.core
jackson-core
2.7.5
com.fasterxml.jackson.core
jackson-annotations
2.7.5
com.fasterxml.jackson.core
jackson-databind
2.7.5
第二步:添加一个类 RestApiConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* * Restful API 访问路径:
* http://IP:port/{context-path}/swagger-ui.html
* eg:http://localhost:8080/swagger-ui.html
* Created by evan on 2018/5/31.
*/
@EnableWebMvc
@EnableSwagger2
@Configuration
public class RestApiConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.evanosc.controller")) // 注意修改此处的包名
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口列表 v1.1.0") // 任意,请稍微规范点
.description("接口测试") // 任意,请稍微规范点
.termsOfServiceUrl("http://localhost:8080/swagger-ui.html") // 将“url”换成自己的ip:port
.contact("evan") // 无所谓(这里是作者的别称)
.version("1.1.0")
.build();
}
}
第三步:添加配置,一般是dispatcher-servlet.xml
OK,自动生成api接口文档就是这么简单,感觉就是前后端分离的利器。
http://localhost:8080/swagger-ui.html