swagger 接口文档生成与导出

1,接口生成

1.1 外部环境

  • jdk1.8
  • spirng-boot :2.0.3.RELEASE

1.2 依赖

<!-- swagger 接口生成插件 -->
		<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>

1.3 配置

WebConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.zcg.modules.base.properties.SwaggerProperties;

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.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@EnableSwagger2
@Configuration
@SuppressWarnings("deprecation")
public class WebConfig extends WebMvcConfigurerAdapter {
	/**
	 * 配置api接口生成插件swagger
	 * @return
	 */
	@Bean
    public Docket createRestApi(SwaggerProperties sp) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(sp))
                .tags(new Tag("product", "产品接口"),getTags())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zcg"))
                .paths(PathSelectors.any())
                .build();
    }
    private Tag[] getTags() {
        Tag[] tags = {
            new Tag("user", "用户接口"),
            new Tag("api_product", "产品内部接口")
        };
        return tags;
    }
    private ApiInfo apiInfo(SwaggerProperties sp) {
        return new ApiInfoBuilder().title(sp.getTitle()).description(sp.getDescription())
        		.version(sp.getVersion())
                .contact(new Contact(sp.getAuthorName(),sp.getAuthorUrl(),sp.getAuthorEmail()))
                .termsOfServiceUrl(sp.getTermsOfServiceUrl()).build();
    }
}

SwaggerProperties

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import lombok.Data;
@Data
@Component
@PropertySource(value = { "classpath:config/properties/pro-swagger.properties" }, encoding = "utf8")
public class SwaggerProperties implements JwtProperties {
	@Value("${swagger.title}")
	private String title;
	@Value("${swagger.description}")
	private String description;
	@Value("${swagger.termsOfServiceUrl}")
	private String termsOfServiceUrl;
	@Value("${swagger.author.name}")
	private String authorName;
	@Value("${swagger.author.email}")
	private String authorEmail;
	@Value("${swagger.author.url}")
	private String authorUrl;
	@Value("${swagger.version}")
	private String version;
}

1.3 定义接口

示例

import org.springframework.http.MediaType;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags= {"api_product"})
@RestController
@RequestMapping("/api/core")
public class ProductApiController{
	@ApiOperation(value="创业方式(添加)" ,notes="添加创业方式")
	@ApiImplicitParams({
		@ApiImplicitParam(name="name" ,value="创业方式名称,非空,最大20个字符" ,required=true ,dataType="string",paramType="query"),
		@ApiImplicitParam(name="description" ,value="描述 ,非必须" ,required=false ,dataType="string",paramType="query")})
	@ApiResponses({
		@ApiResponse(code=200 ,response=JsonResultConstant.class, message="固定返回模型,json字符串表现形式;"),	
		@ApiResponse(code=0 ,response=ProductIntro.class, message="data字段内容,json数组格式,包含多个示例模型")})		
	@PostMapping(value="/add/model" ,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String addModel(
			@ApiIgnore String name ,@ApiIgnore String descrpition) {
		return null;
	}
}

错误提示说明:
JsonResultConstant.class :该类为自定义返回数据实体,在该实体对象中可以使用@ApiModel和@ApiModelPropetry定义字段说明;
ProductIntro.class : 同上
附上JsonResultConstant.class示例

import java.util.HashMap;
import java.util.Map;
import com.zcg.modules.base.util.BeanUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel("固定返回参数")
public class JsonResultConstant {
	/**
	 * 固定字段
	 * 描述:表示该结果成功或失败
	 * 类型:boolean
	 * true 成功
	 * false 失败
	 */
	final static public String JSON_FIELD_STATUS = "status";
	/*
	 * 固定字段
	 * 描述:表示该结果提示信息
	 * 类型:string
	 */
	final static public String JSON_FIELD_MSG = "msg";
	/**
	 * 固定字段
	 * 描述:表示该结果错误信息
	 * 类型:string
	 */
	final static public String JSON_FIELD_ERROR = "error";
	/**
	 * 可变字段
	 * 描述:封装该次请求特有的返回结果;
	 * 类型:json对象
	 */
	final static public String JSON_FIELD_DATA = "data";
	@ApiModelProperty("请求状态码,ture成功,false失败")
	private boolean status;
	@ApiModelProperty("错误提示信息")
	private String msg;
	@ApiModelProperty("错误码,请求失败原因")
	private String error;
	@ApiModelProperty("接口内容,参见《响应消息0》,若无,则接口不返回具体内容")
	private Object data;

1.4 使用

  • 启动项目,并访问/swagger-ui.html

2,接口导出

访问项目:/v2/api-docs ,确认有接口的json格式数据返回;

2.1 利用swagger2markup导出接口

2.1.1 依赖

maven插件的方式

<!-- swagger接口导出与 打包为markup 插件 使用方式: 0,确认系统的 /v2/api-docs 接口可用 1,修改configuration.swaggerInput 
				标签内容,将源地址:http://127.0.0.1:8594/product/v2/api-docs 修改为当前项目可0可访问路径; 2,运行当前项目 
				; 3,进入项目根目录,执行mvn命令:mvn swagger2markup:convertSwagger2markup -->
			<plugin>
				<groupId>io.github.swagger2markup</groupId>
				<artifactId>swagger2markup-maven-plugin</artifactId>
				<version>1.3.1</version>
				<configuration>
					<!-- api-docs访问url -->
					<swaggerInput>http://localhost:8080/product/v2/api-docs</swaggerInput>
					<!-- 生成为单个文档,输出路径 
					<outputFile>src/main/doc/api</outputFile>-->
					<!-- 生成为多个文档,输出路径 -->
					<outputDir>src/main/doc/apiall</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>
2.1.2 依赖插件参数说明:
  • configuration.swaggerInput :该标签内容需修改为需要导出接口项目的/v2/api-docs 路径
  • configuration.outputFile :该标签为生成单个文档指定文档生成路径,如生成txt、md等文件,可随意修改;但注意,该标签与outputDir标签二选一;
  • configuration.outputDir :该标签为生成多个文档指定文档目录,如生成ASCIIDOC文件,该类文件可用于结合asciidoctor插件生成html文件;
  • configuration.config :该标签内定义的swagger2markup.markupLanguage子标签,只能同时存在一个,如指定生成markdown 即md文件时,就不能指定生成其他类型;

注意:指定生成ASCIIDOC文件类型时,需与configuration.outputDir标签配合使用;

2.1.2 使用:
  • 运行当前项目
  • 确认系统的 /v2/api-docs 接口可用
  • 进入项目根目录,进入cmd ,执行mvn命令:mvn swagger2markup:convertSwagger2markup
  • 结果确认:将在configuration.outputDir 或configuration.outputFile标签指定的目录和文件,生成对应的接口文档;

2.2.1 使用asciidoctor配合swagger2markup生成html文件

2.2.2 依赖
<!-- mvn asciidoctor:process-asciidoc -->
			<plugin>
				<groupId>org.asciidoctor</groupId>
				<artifactId>asciidoctor-maven-plugin</artifactId>
				<version>1.5.6</version>
				<configuration>
					<sourceDirectory>src/main/doc/apiall</sourceDirectory>
					<outputDirectory>src/main/doc/api/html</outputDirectory>
					<backend>html</backend>
					<sourceHighlighter>coderay</sourceHighlighter>
					<attributes>
						<toc>left</toc>
					</attributes>
				</configuration>
			</plugin>
2.2.3 依赖配置说明:
  • configuration.sourceDirectory :该标签用于指定利用ASSIIDOC文件生成html的资源目录,即该标签需要与swagger2markup生成的ASSIIDOC文件在同一个目录,一般讲该标签目录设置与swagger2markup插件configuration.outputDir标签内容一致即可;
2.2.4 使用
  • 在利用swagger2markup生成了ASSIIDOC文件之后,将configuration.sourceDirectory 指定到ASSIIDOC文件的目录
  • 进入到项目根路径,使用maven命令:mvn asciidoctor:process-asciidoc
  • 13
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值