Swagger集成
基于HTTP的Webservice相比于基于SOAP协议的Webservice一大缺点就是缺少约束和文档定义,因此我们需要采用Swagger完成对接口的定义,以及相关代码生成等。
依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>配置
开发者需要在入口类上配置@EnableSwagger2启用Swagger的支持。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}接口定义
接口类使用@Api,接口方法使用@ApiOperation,接口参数使用@ApiParam。
对象定义
接口涉及的数据模型(如:DTO/VO等),需要使用Swagger提供的注解进行描述。
数据模型使用@ApiModel,字段使用@ApiModelProperty,推荐对于数据模型中的字段使用example属性配置示例值。
查看定义
配置springfox-swagger-ui的依赖之后,接口文档会随项目启动自动生成。路径为当前应用路径下的/swagger-ui.html,如:http://localhost:8080/swagger-ui.html#/。
参考文档
详细的注解以及参数说明:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X
Last updated