Spring和Swagger文档规范整合详解
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组件中查看,并下载。
首发地址:
品茗IT-同步发布
品茗IT 提供在线支持:
二、环境配置
本文假设你已经引入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:
详细完整的实体,可以访问品茗IT-博客《Spring和Swagger文档规范整合详解》进行查看
全部代码可以在Spring组件化构建https://www.pomit.cn/java/spring/spring.html中的Swagger组件中查看,并下载。
快速构建项目
喜欢这篇文章么,喜欢就加入我们一起讨论SpringBoot技术吧!
品茗IT交流群