swagger的作用
- 自动生成REST API文档,随着代码自动更新。
- 提供了UI界面,既展示接口信息(在线查看),又提供了参数校验,测试功能(在线调试)。
springBoot集成swagger
-
pom下添加依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency>
-
添加swagger配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
* @return
*/
@Bean
public Docket zxApi() {
ParameterBuilder aParameterBuilder = new ParameterBuilder();//添加全局参数
aParameterBuilder.name(“authorization”).defaultValue(“token”).description(“验证TOKEN”).modelRef(new ModelRef(“string”)).parameterType(“header”).required(false).build();
List aParameters = new ArrayList();
aParameters.add(aParameterBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(zxApiInfo())
.groupName(“测试”) //分组
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.globalOperationParameters(aParameters)
.forCodeGeneration(false)
.select()
.apis(RequestHandlerSelectors.basePackage(“zx.privder.controller”))
.paths(PathSelectors.any())
.build();
}/** * 构建 api文档的详细信息函数 * @return */ private ApiInfo zxApiInfo() { return new ApiInfoBuilder() .title("swagger-demo") .description("swagger- demo--创建于2018/4/02") .version("1.0")//版本 .build(); }
}
-
测试 浏览器输入(默认端口8080) http://localhost:8080/swagger-ui.html
swagger常用注解
- @Api 用在类上,类描述
- @ApiOperation 用在方法上,方法描述
- @ApiParam 用在方法参数上
- @ApiModel 用在实体类,类解释
- @ApiModelProperty 用在实体字段,字段解释
注:@Api里的description已废弃,现使用tags更好来分组,如果tags中的值设置为中文, 那么下面的方法名点击将不能被展(英文没这种问题),解决方法可以在swaggerConfig下配置tags或者升级版本
其他
- swagger可以在配置类里配置多个组
- swagger-ui是通过获取接口的json数据渲染页面的,即通过swagger的注解将生成接口的描述服务,默认地址为/v2/api-docs,如果需要改变这个请求地址,可以在properties中配置。例如:springfox.documentation.swagger.v2.path=/swagger。
swagger导出生成html
1)利用swagger2markup插件导出接口
2)使用asciidoctor插件配合swagger2markup生成html文件
<!--swagger2markup插件-->
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<!-- api-docs访问url -->
<swaggerInput>http://localhost:8080/zx/swagger?group=zx</swaggerInput>
<!-- 生成为单个文档,输出路径
<outputFile>src/main/doc/api</outputFile>-->
<!-- 生成为多个文档,输出路径 -->
<outputDir>F:downloadswagger</outputDir>
<config>
<!-- wiki格式文档 -->
<!--<swagger2markup.markupLanguage>CONFLUENCE_MARKUP</swagger2markup.markupLanguage> -->
<!-- ascii格式文档 -->
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
<!-- markdown格式文档 -->
<!--<swagger2markup.markupLanguage>MARKDOWN</swagger2markup.markupLanguage>-->
<swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy>
</config>
</configuration>
</plugin>
<!--asciidoctor插件-->
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<configuration>
<sourceDirectory>F:downloadswagger</sourceDirectory>
<outputDirectory>F:downloadswaggerhtml</outputDirectory>
<backend>html</backend>
<sourceHighlighter>coderay</sourceHighlighter>
<attributes>
<toc>left</toc>
</attributes>
</configuration>
</plugin>
springCloud集成swagger
springcloud 相当于多个springboot的合集,需要把所有的文档放一起集中展示,在zuul下配置总入口即可。 注:分组的话需要配置分组信息,存于swagger.properties中 key为serviceId,value为分组名(多个用逗号隔开)
代码如下:
package zx.cn.zuul.configuration;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
/**
* 分布式swagger文档配置
*/
@Component
@Primary
@Slf4j
@EnableSwagger2
public class ZuulSwaggerConfig implements SwaggerResourcesProvider {
/**版本**/
private final String version = "2.0";
@Autowired
private ZuulProperties properties;
/**
* 构建文档列表
* @return
*/
@Override
public List<SwaggerResource> get() {
//读取属性文件
Properties p = readProperties();
List<SwaggerResource> resources = Lists.newArrayList();
properties.getRoutes().values().stream().forEach((route)->{
String serviceId = route.getServiceId();
String group_property = p.getProperty(serviceId);
//分组
if(StringUtils.isNotBlank(group_property)){
String[] groupNames=group_property.split(",");
for(String groupName:groupNames){
resources.add(createResource(serviceId,serviceId,version,groupName));
}
}else {//未分组
resources.add(createResource(serviceId,serviceId,version));
}
});
return resources;
}
/**
* 构建SwaggerResource(不分组)
* @param name
* @param location
* @param version
* @return
*/
private SwaggerResource createResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation("/" + location + "/v2/api-docs" );
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
/**
* 构建SwaggerResource(分组)
* @param name
* @param location
* @param version
* @param groupName
* @return
*/
private SwaggerResource createResource(String name, String location, String version, String groupName) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation("/" + location + "/v2/api-docs?group=" + groupName);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
/**
* 解析 swagger.properties
* @return
*/
private Properties readProperties() {
Properties p = new Properties();
InputStreamReader in = null;
try {
in = new InputStreamReader(ZuulSwaggerConfig.class.getResourceAsStream("/swagger.properties"), "UTF-8");
p.load(in);
} catch (Exception e) {
e.printStackTrace();
log.error("加载 swagger.properties 属性文件出错,错误信息:" + e.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return p;
}
}
注: springcloud swagger 版本推荐2.7.0 及以上