SpringBoot二十三:整合Swagger2


Swagger3.0

手写Api文档的几个痛点:

  1. 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
  2. 接口返回结果不明确
  3. 不能直接在线测试接口,通常需要使用工具,比如postman
  4. 接口文档太多,不好管理

Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。

其他的不多说,想要了解Swagger的,可以去Swagger官网,可以直接使用Swagger editor编写接口文档,当然我们这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。

swagger-ui

swagger-ui:http://localhost:8080/swagger-ui.html#/

pom文件引入以下依赖

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.9.2</version>
</dependency>

Swagger配置类

其实这个配置类,只要了解具体能配置哪些东西就好了,毕竟这个东西配置一次之后就不用再动了。 特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

@Configuration
@EnableSwagger2 // 开启Swagger
//@Profile({"dev","test"})
//@ConditionalOnProperty(name = "swagger.enable", havingValue = "true") 
public class SwaggerCofing {
	@Bean
	public Docket apiConfig() {
		return new Docket(DocumentationType.SWAGGER_2)
				// .pathMapping("/user")//最终调用接口后会和paths拼接在一起
				// .useDefaultResponseMessages(false)//关闭默认返回值
				.groupName("MYAPI") // 定义分组,默认default
				.apiInfo(apiInfo())// 调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
				.select()// 创建ApiSelectorBuilder对象
				.apis(RequestHandlerSelectors.basePackage("cn.com.javakf.swagger.controller"))// apis()指定扫描的包生成文档
				.paths(PathSelectors.any())
				// .paths(PathSelectors.ant("/user/**"))//选定api的路径
				// .paths(Predicates.or(PathSelectors.regex("/user/.*")))//过滤的接口
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("SpringBoot整合Swagger构建API文档")// 大标题
				.description("简单优雅的restfun风格,https://gitee.com/qiuka/springboot")// 详细描述
				.version("1.0.0")// 版本
				// .termsOfServiceUrl("https://www.baidu.com/")//服务条款
				// .contact(new Contact("qiukang","https://gitee.com/qiuka/springboot","931750352@qq.com"))//作者
				// .license("The Apache License, Version 2.0")//许可证信息
				// .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")//许可证地址
				.build();
	}
}

访问swaggerUI接口文档显示basic-error-controler问题

配置扫描包@ComponentScan(basePackages = {“cn.com.javakf”})时
在这里插入图片描述
解决:

.paths(Predicates.not(PathSelectors.regex("/error.*")))//错误路径不监控

swagger-ui-layer

由于swagger默认的模板是上下分布的,可能有很多人用着感觉很不舒服,在这,我使用了一款第三方的插件,是一般后台的左右式分布,用起来比较舒服
只需要在pom文件中加入如下依赖

<!-- https://mvnrepository.com/artifact/com.github.caspar-chen/swagger-ui-layer -->
<dependency>
	<groupId>com.github.caspar-chen</groupId>
	<artifactId>swagger-ui-layer</artifactId>
	<version>1.1.3</version>
</dependency>

swagger-ui-layer 的默认访问地址是 http:// h o s t : {host}: host:{port}/docs.html
启动项目之后访问:http://localhost:8080/docs.html
在这里插入图片描述
注意: swagger api 的默认地址是/v2/api-docs 所以swagger-ui-layer也读取的是默认地址, 所以在new Docket()的时候不能指定group参数,否则 swagger api 的地址会在后面加入group的参数导致swagger-ui-layer不能正确请求到数据

swagger-bootstrap-ui

<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.5</version>
</dependency>

Swagger-Bootstrap-UI 基于Swagger 的前端UI ,采用jQuery+bootstrap实现。
因Swagger 的默认UI 是上下结构的,用起来不太习惯,所以用Swagger-Bootstrap-UI 替换Swagger 默认的UI实现左右菜单风格的Swagger-UI ,让其看起来更清晰明了
默认访问地址:http:// h o s t : {host}: host:{port}/doc.html
http://localhost:8080/doc.html

swagger2markup

1、maven坐标

<!-- https://mvnrepository.com/artifact/io.github.swagger2markup/swagger2markup -->
<dependency>
	<groupId>io.github.swagger2markup</groupId>
	<artifactId>swagger2markup</artifactId>
	<version>1.3.3</version>
</dependency>

2、添加maven打包成html的方式

<plugin>
	<groupId>org.asciidoctor</groupId>
	<artifactId>asciidoctor-maven-plugin</artifactId>
	<version>1.5.6</version>
	<configuration>
		<sourceDirectory>./docs/asciidoc/generated</sourceDirectory>
		<outputDirectory>./src/main/resources/static/v1</outputDirectory>
		<headerFooter>true</headerFooter>
		<doctype>book</doctype>
		<backend>html</backend>
		<sourceHighlighter>coderay</sourceHighlighter>
		<attributes>
			<!--菜单栏在左边 -->
			<toc>left</toc>
			<!--多标题排列 -->
			<toclevels>3</toclevels>
			<!--自动打数字序号 -->
			<sectnums>true</sectnums>
		</attributes>
	</configuration>
</plugin>

3、测试类 运行(首先必须要运行项目 在运行测试类 因为是通过项目的url 默认 v2/api-docs 解析json数据)

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
public class swagger2markupTest {

	// 接口数据json访问路径
	private final String URL = "http://localhost:8080/v2/api-docs";

	/**
	 * 生成AsciiDocs格式文档
	 *
	 * @throws Exception
	 */
	@Test
	public void generateAsciiDocs() throws Exception {
		// 输出Ascii格式
		Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.ASCIIDOC)
				.withOutputLanguage(Language.ZH).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples()
				.withoutInlineSchema().build();

		Swagger2MarkupConverter.from(new URL(URL)).withConfig(config).build()
				.toFolder(Paths.get("./docs/asciidoc/generated"));
	}

	/**
	 * 生成Markdown格式文档
	 *
	 * @throws Exception
	 */
	@Test
	public void generateMarkdownDocs() throws Exception {
		// 输出Markdown格式
		Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.MARKDOWN)
				.withOutputLanguage(Language.ZH).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples()
				.withoutInlineSchema().build();

		Swagger2MarkupConverter.from(new URL(URL)).withConfig(config).build()
				.toFolder(Paths.get("./docs/markdown/generated"));
	}

	/**
	 * 生成Confluence格式文档
	 *
	 * @throws Exception
	 */
	@Test
	public void generateConfluenceDocs() throws Exception {
		// 输出Confluence使用的格式
		Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
				.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP).withOutputLanguage(Language.ZH)
				.withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples().withoutInlineSchema().build();

		Swagger2MarkupConverter.from(new URL(URL)).withConfig(config).build()
				.toFolder(Paths.get("./docs/confluence/generated"));
	}

	/**
	 * 生成AsciiDocs格式文档,并汇总成一个文件
	 *
	 * @throws Exception
	 */
	@Test
	public void generateAsciiDocsToFile() throws Exception {
		// 输出Ascii到单文件
		Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.ASCIIDOC)
				.withOutputLanguage(Language.ZH).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples()
				.withoutInlineSchema().build();

		Swagger2MarkupConverter.from(new URL(URL)).withConfig(config).build()
				.toFile(Paths.get("./docs/asciidoc/generated/all"));
	}

	/**
	 * 生成Markdown格式文档,并汇总成一个文件
	 *
	 * @throws Exception
	 */
	@Test
	public void generateMarkdownDocsToFile() throws Exception {
		// 输出Markdown到单文件
		Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.MARKDOWN)
				.withOutputLanguage(Language.ZH).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples()
				.withoutInlineSchema().build();

		Swagger2MarkupConverter.from(new URL(URL)).withConfig(config).build()
				.toFile(Paths.get("./docs/markdown/generated/all"));
	}

	@Test
	public void generateDosc() throws Exception {
		generateAsciiDocs();
		generateMarkdownDocs();
		generateConfluenceDocs();
		generateAsciiDocsToFile();
		generateMarkdownDocsToFile();
	}

}

4、使用 maven命令打包(docs文件路径为当项目路径的docs,也就是解析json后的数据文档)

asciidoctor:process-asciidoc

5、访问静态文件,生成all.html后(路径和文件名可自己修改) 再重启项目
在这里插入图片描述
http://localhost:8080/v1/all.html
在这里插入图片描述
默认 v2/api-docs可能访问springboot自带的controller,可通过配置修改 json数据url

#Swagger 相关配置
springfox:
 documentation:
  swagger:
   v2:
    path: /ucs/swagger.json

在生产环境下,我们需要关闭swagger配置,避免暴露接口的这种危险行为。

禁用方法1: 使用注解@Profile({“dev”,“test”}) 表示在开发或测试环境开启,而在生产关闭。(推荐使用)
禁用方法2: 使用注解@ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”) 然后在测试配置或者开发配置中 添加 swagger.enable = true 即可开启,生产环境不填则默认关闭Swagger.

Swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

@Api:修饰整个类,描述Controller的作用

该注解将一个Controller(Class)标注为一个swagger资源(API)。在默认情况下,Swagger-Core只会扫描解析具有@Api注解的类,而会自动忽略其他类别资源(JAX-RS endpoints,Servlets等等)的注解。

  • tags:API分组标签。具有相同标签的API将会被归并在一组内展示。
  • value:如果tags没有定义,value将作为Api的tags使用
  • description:API的详细描述,在1.5.X版本之后不再使用,但实际发现在2.0.0版本中仍然可以使用
    在这里插入图片描述

@ApiOperation:描述一个类的一个方法,或者说一个接口

在指定的(路由)路径上,对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。

  • value:对操作的简单说明,长度为120个字母,60个汉字。
  • notes:对操作的详细说明。
  • httpMethod:HTTP请求的动作名,可选值有:“GET”, “HEAD”, “POST”, “PUT”, “DELETE”,
    “OPTIONS” and “PATCH”。
  • code:默认为200,有效值必须符合标准的HTTP Status Code Definitions。
    在这里插入图片描述

@ApiParam:单个参数描述

增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。

  • required:是否为必传参数
  • value:参数简短说明
    在这里插入图片描述

@ApiModel:用对象来接收参数

提供对Swagger model额外信息的描述。在标注@ApiOperation注解的操作内,所有的类将自动被内省(introspected),但利用这个注解可以做一些更加详细的model结构说明。

  • value:model的别名,默认为类名
  • description:model的详细描述
    在这里插入图片描述

@ApiModelProperty:用对象接收参数时,描述对象的一个字段

在这里插入图片描述
在这里插入图片描述

@ApiResponses:HTTP响应整体描述

注解@ApiResponse的包装类,数组结构。即使需要使用一个@ApiResponse注解,也需要将@ApiResponse注解包含在注解@ApiResponses内。

@ApiResponse:HTTP响应其中1个描述

描述一个操作可能的返回结果。当REST API请求发生时,这个注解可用于描述所有可能的成功与错误码。可以用,也可以不用这个注解去描述操作的返回类型,但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型,那么需要分别定义返回值,并将返回类型进行关联。但Swagger不支持同一返回码,多种返回类型的注解。注意:这个注解必须被包含在@ApiResponses注解中。

  • code:HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions。code必须与http
    code相对应,否则会报错
  • message:更加易于理解的文本消息
  • response:返回类型信息,必须使用完全限定类名,比如“com.xyz.cc.Person.class”。
  • responseContainer:如果返回类型为容器类型,可以设置相应的值。有效值为 “List”, “Set” or
    “Map”,其他任何无效的值都会被忽略。
    在这里插入图片描述

@ApiIgnore:使用该注解忽略这个API

@ApiImplicitParams:多个请求参数

注解ApiImplicitParam的容器类,以数组方式存储。

@ApiImplicitParam:一个请求参数

对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定,但这个@ApiImplicitParam注解可以以统一的方式定义参数列表,也是在Servelet及非JAX-RS环境下,唯一的方式参数定义方式。注意这个注解@ApiImplicitParam必须被包含在注解@ApiImplicitParams之内。

  • name:参数名称
  • value:参数的简短描述
  • required:是否为必传参数
  • dataType:参数类型,可以为类名,也可以为基本类型(String,int、boolean等)
  • paramType:参数的传入(请求)类型,可选的值有path, query, body, header or form。
    在这里插入图片描述
    代码托管:springboot_swagger
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值