陈述
swagger可嵌入api文档书写
手写文档的痛点:
1. 文档更新交流不及时,文档的更新后需再次发送给到前端。
2. 接口返回结果不明确
3. 不能直接在线测试接口
4. 接口文档较多不好管理
swagger的缺点是代码移入性较强
嵌入spring-boot
- maven 引用
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
我使用的spring-boot版本比较老,spring-aop包有冲突,排除了spring-boot中引入的spring-aop版本,引入了新的版本。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.11.RELEASE</version>
</dependency>
- 实例化实体&实现接口
初始化bean,设置文档简介
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage(basePackage)) // 指向文档注解包路径
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title) // 文档标题
.description(description) // 文档简介
.termsOfServiceUrl(termsOfServiceUrl) // 服务条款连接
.version(version) // 版本
.build();
}
接口方法
@ApiOperation(value = "添加用户", notes = "添加详细的用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "UserInfo", paramType = "body")
})
@RequestMapping(value = "add", method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public JSONObject addUser(@RequestBody UserInfo user) {
JSONObject json = new JSONObject();
try {
json.put("data", userService.addUser(user));
json.put("success", true);
} catch (Exception e) {
e.printStackTrace();
json.put("message", e.getMessage());
json.put("success", false);
}
return json;
}
@ApiOperation(value = "添加用户", notes = "添加详细的用户信息")
在@ApiOperation注解中,value是接口简介,notes是接口详细介绍
@ApiImplicitParams({
@ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "UserInfo", paramType = "body")
})
@ApiImplicitParams是多个参数时使用,而@ApiImplicitParam是一个参数的详细介绍。
@ApiImplicitParam中,name对应接口参数名,value是参数介绍,required是是否必传参数,dataType是参数类型,也可以是实体。paramType是请求的参数位置,类型有path、query、body、header、from。
path是请求路径上的参数
query是请求路径后面?后的参数
body是放置在requerybody中的参数
header是防止在requeryheader中的参数
from是表单
@ApiIgnore
@ApiIgnore是该接口不生产接口文档
- 访问地址