- 使用原因 :本人以前做项目的时候都是前后端都写的,所以一般使用的测试接口工具是postman,重要的接口都是测试一个保存一个方便自己以后调试使用。其中许多方式传参还是值得考究的,这里就不做介绍了!后来!前端终于不用自己写了,那么如何把接口提供出去而又不用手写接口文档呢?所有在就使用了Swagger。
- 简单说下,它的出现就是为了方便进行测试后台的restful形式的接口,实现动态的更新,当我们在后台的接口修改了后,swagger可以实现自动的更新,而不需要认为的维护这个接口进行测试。
-
正式部署起来吧~
- springBoot集成swagger2
- springBoot 版本
1.5.10.RELEASE
- swagger2 版本
RELEASE
创建springBoot项目在pom.xml中导入所需jar包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
4.swagger的驱动配置类
package org.linlinjava.litemall.wx;
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.service.Contact;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by wo on 2018/8/16.
*/
//注解开启 swagger2 功能
@EnableSwagger2
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())//调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
.select()
//控制暴露出去的路径下的实例
//如果某个接口不想暴露,可以使用以下注解
//@ApiIgnore 这样,该接口就不会暴露在 swagger2 的页面下
.apis(RequestHandlerSelectors.basePackage("org.linlinjava.litemall.wx.web"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot 海车项目Api接口 RestFul API")
//创建人
.contact(new Contact("Timothy", "http://www.haiche.com", ""))
//版本号
.version("1.0")
//描述
.description("小程序后端接口")
.build();
}
}
- 注意所存的位置是和springboot的驱动类同级存在
- 在springBoot的驱动类写@EnableSwagger2
-
代码接口编写
@ApiOperation("默认获取开通地区信息")
@GetMapping(value = "/openAddress", produces = {"application/json;charset=UTF-8"})
public JsonFormat openAddress(){
try {
logger.info("获取开通地区接口信息---->".concat("openAddress HTTP/GET"));
return new JsonFormat(ConstantCode.SUCCESS,"SUCCESS",haiCheOpenAddressService.openAddress());
}catch (Exception e){
e.printStackTrace();
return new JsonFormat(ConstantCode.ERROR,"服务器错误", null);
}
}
- 启动项目-打开swagger页面 地址: http://localhost:项目端口/项目名称/swagger-ui.html
- 如下图