1.使用swagger2的好处
在日常开发中,避免不了的就是为接口编写文档。这需要占用我们一定的开发时间。同时还需要维护接口文档,当接口字段有变化,我们需要立即更新文档,而且还需要告知前端。进行修改。现在我们可以使用swagger2来帮助我们在线生成接口文档,接口文档自动更新等等,接口测试等等。swagger2使用很简单,其只会对现在的代码结构有微小的变化。这也是合理的!
2.继承swagger2
1.在pom文件中添加上依赖
<!--swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.添加Swagger2 config
package com.my.webapp.app;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.my.webapp.app.controller"))//暴露指定包下的接口说明,可以指定多个包
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("webapp接口文档")
.description("webapp开放接口相关文档,仅供学习,研究使用!")
.termsOfServiceUrl("")
.contact(new Contact("struggling_rong", "", "xxx@xx.com"))
.version("1.0.0")
.build();
}
}
注意需要该Config类所处的包要被springboot启动时扫描到swagger2才能生效。
否则会出现如下提示
3.为接口编写说明
接口类,方法,参数,返回值的说明都是通过swagger2提供的注解来完成
package com.my.webapp.app.controller;
import com.my.webapp.app.controller.param.EncryptParam;
import com.my.webapp.app.controller.response.Response;
import io.swagger.annotations.*;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
/**
*/
@Api(tags = "测试", produces = MediaType.APPLICATION_JSON_VALUE)//整个类的说明
@RestController
@RequestMapping("/test")
public class TestController extends BaseController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.profiles.active}")
private String profileActive;
@Autowired
private StringEncryptor jasyptStringEncryptor;
@ApiOperation(value = "加密", produces = MediaType.APPLICATION_JSON_VALUE)//方法说明
@ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Response.class)})//响应数据说明,可以有多个
@RequestMapping(value = "/encrypt", method = RequestMethod.POST)
public Response encrypt(@RequestBody @Valid EncryptParam param) {
return Response.success(jasyptStringEncryptor.encrypt(param.getText()));
}
@RequestMapping(value = "/decrypt/{cipherText}", method = RequestMethod.POST)
public Response decrypt(@PathVariable @ApiParam(value = "密文", required = true) String cipherText) {
return Response.success(jasyptStringEncryptor.decrypt(cipherText));
}
}
@Api(tags=”测试”, produces = MediaType.APPLICATION_JSON_VALUE)
作用于类,表示该类为swagger2的一个资源,我们还可以使用@ApiIgnore让swagger2忽略该类
tags: 说明
produces: 数据格式
@ApiOperation(value = “加密”, produces = MediaType.APPLICATION_JSON_VALUE)
作用于方法,用于说明方法
value: 说明
produces: 数据格式
@ApiResponses(value = {@ApiResponse(code = 200, message = “成功”, response = Response.class)})
作用于方法,说明方法的返回数据,
value: 多个@ApiResponse集合
@ApiResponse:某种情况的回复数据,可以有多个
code:响应code 如200, 404, 201等
message: 响应数据说明
response: 响应数据类型
@ApiParam(value=”密文”, required = true)
作用于方法,说明参数
value: 说明
required: 是否必填
当参数是个复杂的类,我们还可以使用@ApiModule和@ApiModelProperty两个注解来搭配使用
package com.my.webapp.app.controller.param;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.validator.constraints.NotBlank;
/**
*/
@ApiModel("加密参数")
public class EncryptParam {
@ApiModelProperty(value = "明文", required = true)//参数说明
@NotBlank
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
@ApiModule(“加密参数”)
用于整个类的说明
@ApiModelProperty(value = “明文”, required = true)
用于某个字段的说明
value:说明
required: 是否必填
4.使用swagger2生成的在线文档
启动项目后
通过浏览器打开
http://localhost:8080/swagger-ui.html
则效果如下:
如果我们需要测试该接口,可以点击try it out 按钮进行测试。
参考链接:
Spring Boot中使用Swagger2构建强大的RESTful API文档
swagger2常用注解说明