前言
官方描述文档地址 : http://springfox.github.io/springfox/docs/current/
官方api地址 :http://springfox.github.io/springfox/javadoc/current/
1. 引入maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
2. 引入springfox-swagger配置
package com.jt.event.log.config;
import org.joda.time.DateTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.UriComponentsBuilder;
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.paths.AbstractPathProvider;
import springfox.documentation.spring.web.paths.Paths;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
/**
* 官方文档地址: http://springfox.github.io/springfox/docs/current/
* Docket,Springfox的主要api配置机制已针对swagger规范2.0进行了初始化
* select()返回的实例,ApiSelectorBuilder以对通过摇摇杆暴露的端点进行精细控制
* apis()允许RequestHandler使用谓词选择。此处的示例使用any谓词(默认)。出所提供的框中谓词的是any,none,withClassAnnotation,withMethodAnnotation和 basePackage。
* paths()允许Path使用谓词选择。此处的示例使用any谓词(默认)。出我们对于提供谓词盒子regex,ant,any,none。
* build() 在配置api和path选择器之后,需要构建选择器。
* directModelSubstitute() 渲染模型属性时将替换LocalDate为的便利规则构建器String
* useDefaultResponseMessages() 标记,指示是否需要使用默认的http响应代码。
* enableUrlTemplating 生成的路径应尝试使用 表单样式查询扩展
* @return
*/
@Bean
public Docket latestDocumentationPlugin() {
return new VersionedDocket("v2");
}
@Bean
public Docket v10DocumentationPlugin() {
return new VersionedDocket("v1");
}
class VersionedDocket extends Docket {
public VersionedDocket(String version) {
super(DocumentationType.SWAGGER_2);
super.groupName(version)
.select()
.apis(RequestHandlerSelectors.any())
.paths(regex("/" + version + "/.*"))
.build()
.apiInfo(getApiInfo(version))
.pathProvider(new BasePathAwareRelativePathProvider("/api/" + version))
.directModelSubstitute(DateTime.class, String.class)
.useDefaultResponseMessages(false)
.enableUrlTemplating(true);
}
private ApiInfo getApiInfo(String version) {
return new ApiInfoBuilder()
.title("高速智慧平台接口文档")
.description("springboot swagger2")
.version(version)
.termsOfServiceUrl("http://blog.csdn.net/u014231523网址链接")
.contact(new Contact("bin", "http://blog.csdn.net/u014231523", "111@163.com"))
.build();
}
}
class BasePathAwareRelativePathProvider extends AbstractPathProvider {
private String basePath;
public BasePathAwareRelativePathProvider(String basePath) {
this.basePath = basePath;
}
@Override
protected String applicationPath() {
return basePath;
}
@Override
protected String getDocumentationPath() {
return "/";
}
@Override
public String getOperationPath(String operationPath) {
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromPath("/");
return Paths.removeAdjacentForwardSlashes(
uriComponentsBuilder.path(operationPath.replaceFirst(basePath, "")).build().toString());
}
}
}
该配置区分了url的版本,如果url 为 v1/** 则放在 v1,如果url 为 v2/** ,则放在v2
如下图,提供了一个base url ,之前就相当于设置了这个base url 的值
3. 文档注解
注解官方文档地址:http://docs.swagger.io/swagger-core/current/apidocs/index.html?io/swagger/annotations
常用的主要有一下注解:
- @Api()用于类名
- @ApiOperation()用于方法名
- @ApiParam()用于参数说明
- @ApiModel()用于实体类
- @ApiModelProperty用于实体类属性
如果想使用application.properties
,application.yml
文件或属性文件中定义属性, 你可以直接引用spring 配置文件属性,例如,@ApiModelProperty(value="${property1.description}")
将 property1.description 定义在application.yml即可。
4. 示例
restController如下:
@Api(value="气象数据查询", tags={"气象数据查询接口"})
@RestController
public class WeatherService {
@Autowired
WeatherEsUtil weatherEsUtil;
@ApiOperation("查取最近的气象条数")
@PostMapping("/v1/getLatestWeatherEvent")
public ResponseBase getLatestWeatherEvent(@RequestBody DeviceLatestParam param) {
if(param.getPageStart() != null){
param.setPageStart(param.getPageStart() - 1);
}
List<WeatherMessage> messages = weatherEsUtil.getLatestWeatherMessage(param);
return new ResponseBase(0, 1, messages, "Get weather message OK");
}
@ApiOperation("查询气象事件")
@PostMapping("/v1/weatherEvent")
public ResponseBase searchWeatherEvents(@RequestBody WeatherParam param) {
ResponseItem responseItem = weatherEsUtil.searchWeatherEvent(param);
if (responseItem == null) {
return new ResponseBase(1, 0, null, "Error get weather events");
}
return new ResponseBase(0, responseItem.getNum().intValue(),
responseItem.getMessageList(), "get weather events ok");
}
model如下:
@ApiModel(description="气象查询对象")
public class WeatherParam {
@ApiModelProperty(value="开始时间")
private String startTime = Constants.initString;
@ApiModelProperty(value="结束时间")
private String endTime = Constants.initString;
@ApiModelProperty(value="结束时间")
private String name = Constants.initString;
@ApiModelProperty(value="开始页")
private Integer pageStart = Constants.initInteger;
@ApiModelProperty(value="页数")
private Integer pageSize = Constants.initInteger;
@ApiModelProperty(value="排序字段")
private String sort = Constants.initString;
@ApiModelProperty(value="排序方向")
private String sortDirection = Constants.initString;
}
最终展示效果:
到现在,spring boot 集成 Swagger2 就完成了!!!