日常开发中,前后端的开发联调都需要定义一个接口文档,定义接口文档是比较耗时的,这边推荐一款插件来根据接口来自动生成接口文档,并且会根据接口的变化而自动更新,解放一部分开发人力。spring boot集成swagger非常简单,只需要以下四步:
1. 引入swagger依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2. 编写config类
@EnableSwagger2
@Configuration
public class Swagger2Config {
@Value("${swagger.enabled:true}")
private boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 要扫描的包(包含其子包)
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("网页的title")
.description("网站的描述(例如:管理平台dev)")
//添加一个联系人,参数分别为姓名,个人网站地址,邮箱
.contact(new Contact("name", "url", "email"))
.version("1.0.0")
.build();
}
}
3. 在要生成的文档的接口上添加注解
@RestController
@Api(value = "用于测试", tags = "用于测试的controller")
public class HelloTest {
@GetMapping("/hello/test")
@ApiOperation(value = "测试方法", notes = "用于测试的方法")
public void test(@RequestParam String param){
System.out.println("hello world");
}
}
这里的代码只是举个例子,@Api可以指定对这个类的描述,@ApiOperation则是指定对方法的描述,这些注解可以不写,插件也会生成文档,但是可读性会略差一点,另外,除了这两个注解外,还有其他功能的注解:
@ApiParam(name = “参数名称”, value = “备注说明”, required = 是否必须):标注在方法的参数上 用于描述参数的名称、备注、是否必须等信息
@ApiImplicitParams: 用于包含多个@ApiImplicitParam
@ApiImplicitParam用于描述方法的参数,标注在方法上,和@ApiParam功能一样,只是标注的位置不同而已
@ApiImplicitParams: 用于包含多个@ApiImplicitParam
@ApiResponse(code = 0, message = “success”)
@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
@ApiIgnore:用于或略该接口,不生成该接口的文档
当然,常用的还是上面的那两个,有兴趣的可以看一下其它的注解的使用。
4. 启动项目,访问文档url
启动项目,并访问http://127.0.0.1/swagger-ui.html
注意:我这边的配置如下:
server.port=80
server.servlet.context-path=/
访问url根据实际的配置自行修改。访问结果如下:
从图中可以看出,我们接口需要哪些参数,是否必填,我们也可以直接在网页上填写参数,并调用接口,查看接口的返回,等于是支持了在线测试接口了。