前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring和Swagger文档规范整合详解

Spring和Swagger文档规范整合详解

作者头像
品茗IT
发布2019-09-12 09:47:11
1.2K0
发布2019-09-12 09:47:11
举报
文章被收录于专栏:品茗IT品茗IT

Spring和Swagger文档规范整合详解

一、概述

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新 。接口的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

swagger可以与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能 来调试每个RESTful API。

代码可以在Spring组件化构建https://www.pomit.cn/java/spring/spring.html中的RabbitMQ组件中查看,并下载。

**如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以<a

href="https://jq.qq.com/?_wv=1027&k=52sgH1J"

target="_blank">

加入我们的java学习圈,点击即可加入

</a>

,共同学习,节约学习时间,减少很多在学习中遇到的难题。**

二、环境配置

本文假设你已经引入Spring必备的一切了,已经是个Spring项目了,如果不会搭建,可以打开这篇文章看一看《Spring和Spring Mvc 5整合详解》

2.1 maven依赖

使用swagger需要引入springfox-swagger2,如果要使用swagger的界面,需要引入springfox-swagger-ui。

<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.pomit</groupId>
		<artifactId>SpringWork</artifactId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<artifactId>Swagger</artifactId>
	<packaging>jar</packaging>
	<name>Swagger</name>
	<url>http://maven.apache.org</url>
	<properties>
		<!-- redis 版本 -->
		<redis.version>2.9.0</redis.version>
		<spring.redis.version>2.0.10.RELEASE</spring.redis.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
		</dependency>

		<!--log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
		</dependency>
		
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>Swagger</finalName>
	</build>
</project>

父模块可以在https://www.pomit.cn/spring/SpringWork/pom.xml获取。

除了依赖,这里使用注解,将不需要其他配置。

三、Swagger配置

3.1 启动Swagger

SwaggerConfig:

package cn.pomit.springwork.swagger.config;

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

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableWebMvc
@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("cn.pomit.springwork"))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("API文档")
				.description("简单优雅的restful风格")
				.version("1.0")
				.build();
	}

}

这里,@EnableSwagger2开启Swagger。@EnableWebMvc注解加上才能正常显示Swagger的界面,不加的话页面根本打不开。

3.2 手动增加Swagger接口说明

有时候,Swagger是获取不到一些接口的信息,这样在界面上就无法显示出这些接口信息。如由SpringSecurity控制的登入等登出接口,这时候我们可以手动添加这些接口:

SwaggerAddtionScanConfig:

package cn.pomit.springwork.swagger.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import com.fasterxml.classmate.TypeResolver;

import cn.pomit.springwork.swagger.entity.TestEntity;
import springfox.documentation.builders.OperationBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiDescription;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ApiListingScannerPlugin;
import springfox.documentation.spi.service.contexts.DocumentationContext;
import springfox.documentation.spring.web.readers.operation.CachingOperationNameGenerator;

/**
 * 该文件可有可无,手动增加接口的方法
 * @author fufei
 *
 */
@Component
public class SwaggerAddtionScanConfig implements ApiListingScannerPlugin {
	@Override
	public List<ApiDescription> apply(DocumentationContext documentationContext) {
		return new ArrayList<>(
				Arrays.asList(
						new ApiDescription("Login", "/login", "登录接口",
								Collections
										.singletonList(
												new OperationBuilder(new CachingOperationNameGenerator()).authorizations(new ArrayList<>())
														.method(HttpMethod.POST)
														.summary("登录接口")                                                
														.notes("登录接口")//方法描述                                                
														.tags(Collections.singleton("登录登出模块"))//归类标签
														.produces(Collections.singleton("application/json"))
														.consumes(Collections.singleton("application/json"))
														.parameters(
																Arrays.asList(
																		new ParameterBuilder()
																				.description("email")
																				.type(new TypeResolver()
																						.resolve(String.class))
																				.name("email")
																				.parameterType("query")
																				.parameterAccess("access")
																				.required(true)
																				.modelRef(new ModelRef("string"))
																				.build(),
																		new ParameterBuilder()
																		.description("password")
																		.type(new TypeResolver()
																				.resolve(String.class))
																		.name("password")
																		.parameterType("query")
																		.parameterAccess("access")
																		.required(true)
																		.modelRef(new ModelRef("string"))
																		.build()
																				))
														.responseMessages(responseMessages())
														.build()),
								false),
						new ApiDescription("Login",
								"/logout", "登出接口",
								Collections
										.singletonList(
												new OperationBuilder(new CachingOperationNameGenerator()).authorizations(new ArrayList<>())
														.method(HttpMethod.POST)
														.summary("登出接口")                                                
														.notes("登出接口")//方法描述                                                
														.tags(Collections.singleton("登录登出模块"))//归类标签
														.produces(Collections.singleton("application/json"))
														.parameters(
																Collections
																		.singletonList(new ParameterBuilder()
																				.description("token")
																				.type(new TypeResolver()
																						.resolve(String.class))
																				.name("token")
																				.parameterType("query")
																				.parameterAccess("access")
																				.required(true)
																				.modelRef(new ModelRef("string"))
																				.build()))
														.responseMessages(responseMessages())
														
														.build()),
								false)));

	}

	/**
	 * @return Set of response messages that overide the default/global response
	 *         messages
	 */
	private Set<ResponseMessage> responseMessages() { // <8>
		return Collections.singleton(
				new ResponseMessageBuilder().code(200).message("Successfully received bug 1767 or 2219 response")
						.responseModel(new ModelRef(
								TestEntity.class.getSimpleName())
								).build());
	}

	@Override
	public boolean supports(DocumentationType documentationType) {
		return DocumentationType.SWAGGER_2.equals(documentationType);
	}
}

四、测试Swagger

我们使用一些Swagger的注解来做测试,如果不加注解其实也是可以的,但是不方便观看,加注解的话可以显示写的内容。

SwaggerRest :

package cn.pomit.springwork.swagger.web;

import java.util.UUID;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.pomit.springwork.swagger.entity.TestEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = {"测试模块"}, produces = "application/json")
@RestController
@RequestMapping("/swagger")
public class SwaggerRest {
	
	@ApiOperation(value = "测试swagger的功能")
	@RequestMapping(value = "/test", method = { RequestMethod.GET })
	public TestEntity test(@RequestParam String reqType) {
		String uuid = UUID.randomUUID().toString();
		String welMsg = "welcome 程序猿";
		if (reqType != null && "1000".equals(reqType)) {
			welMsg = "welcome 程序媛";
		}
		TestEntity welEntity = new TestEntity();
		welEntity.setUuid(uuid);
		welEntity.setWelMsg(welMsg);
		return welEntity;
	}
	
	@RequestMapping(value = "/test2", method = { RequestMethod.GET })
	public TestEntity test2(@RequestParam String reqType) {
		String uuid = UUID.randomUUID().toString();
		String welMsg = "welcome 程序猿";
		if (reqType != null && "1000".equals(reqType)) {
			welMsg = "welcome 程序媛";
		}
		TestEntity welEntity = new TestEntity();
		welEntity.setUuid(uuid);
		welEntity.setWelMsg(welMsg);
		return welEntity;
	}
}

五、过程中用到的实体

TestEntity:

package cn.pomit.springwork.swagger.entity;

public class TestEntity {
	private String uuid;
	private String welMsg;
	public String getUuid() {
		return uuid;
	}
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	public String getWelMsg() {
		return welMsg;
	}
	public void setWelMsg(String welMsg) {
		this.welMsg = welMsg;
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Spring和Swagger文档规范整合详解
  • 一、概述
  • 二、环境配置
    • 2.1 maven依赖
    • 三、Swagger配置
      • 3.1 启动Swagger
        • 3.2 手动增加Swagger接口说明
        • 四、测试Swagger
        • 五、过程中用到的实体
        相关产品与服务
        Serverless HTTP 服务
        Serverless HTTP 服务基于腾讯云 API 网关 和 Web Cloud Function(以下简称“Web Function”)建站云函数(云函数的一种类型)的产品能力,可以支持各种类型的 HTTP 服务开发,实现了 Serverless 与 Web 服务最优雅的结合。用户可以快速构建 Web 原生框架,把本地的 Express、Koa、Nextjs、Nuxtjs 等框架项目快速迁移到云端,同时也支持 Wordpress、Discuz Q 等现有应用模版一键快速创建。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档