【实践笔记】Spring MVC中Restful API使用 Swagger2 构建

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zhaky/article/details/64906686
介绍:

1、Swagger2是什么?

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。

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

2、Swagger2官网

3.Swagger2的入门教程

在微服务架构流行的今天,RESTful API成了服务间交互的主要方式之一,Swagger则成为服务之间的契约描述、提高调试、测试效率的重要工具。 Swagger工具包括Swagger Editor、Swagger UI、Swagger Codegen:

  • Swagger Editor——支持编辑Swagger API规范yaml文档描述API,并可实时预览API。
  • SwaggerUI——API在线文档生成和测试的工具,可显示API描述,并且支持调用API进行测试及验证。
  • Swagger Codegen——一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端SDK或Server端桩代码,从而让开发团队能够更好的关注API的实现和调用,提高开发效率.

3.1Swagger2的maven依赖

 
  
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>

3.2SwaggerConfig的配置

 
  
/**
* Created by Zhaky on 2017/3/17.
* @项目名称:XXXXX
* @类名:SwaggerConfig
* @类的描述: Restapi SwaggerConfig的基本配置
* @作者:Zhaky
* @创建时间:2017/3/17
* @公司:xiaomi
* @QQ:411172392
* @邮箱:[email protected]
* @使用方法:Restful API 访问路径: http://localhost:{port}/{ProjectName}/swagger-ui.html
*/

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableWebMvc
@EnableSwagger2//启用Swagger2
@Configuration//让Spring来加载该类配置
@ComponentScan(basePackages ="com.xiaomi.XXXX")
public class SwaggerConfig {

@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xiaomi.XXXX"))//controller路径
.paths(PathSelectors.any())
.build();
}

private ApiInfo buildApiInf() {
return new ApiInfoBuilder()
.title("开放接口API")
.termsOfServiceUrl("https://XXXXXXX/openapi/")
.description("XXXXXX")
.contact(new Contact("[email protected]", "https://XXXXX.com/", "[email protected]"))
.version("1.0")
.build();

}
}

3.3在Controller中添加

 
  

/**
*
* Created by Zhaky on 2017/1/23.
*/
@RestController
@RequestMapping("/pay")
@Api(value = "XXXController", description = "查询相关操作")
public class XXXController {
private final static Logger logger = LoggerFactory.getLogger(XXXController.class);
@Resource
private LogServiceImpl logServiceImpl;

/**
* 查询
*/
@ApiOperation(value = "XX查询", notes = "查询信息")
@RequestMapping(value = {"/payQuery"}, method = {RequestMethod.POST})

public
@ResponseBody
void payQuery(@RequestBody @Valid PayQuery requestVO, BindingResult result, HttpServletRequest req, HttpServletResponse resp) {
try {
ExecutorService pool = Executors.newCachedThreadPool();
pool.execute(new Runnable() {
@Override
public void run() {
log(req);
};//省略业务逻辑代码
})}}

对于@RequestBody 标记的表单参数实体必须在实体中添加@ApiModel注解

@ApiModel(description = "查询请求表单实体")
@XmlType(name="PayQuery")
public class PayQuery extends BaseBody {

@NotNull(message = "{common.oriReqMsgId.not.empty}")
@Length(min=0, max=32)
@ApiModelProperty(value = "原交易流水号oriReqMsgId", example = "273453459302",position = 1)
private String oriReqMsgId;//原交易流水号
//省略部分代码
}

遇到的问题

Swagger-ui.html 404问题

按照上述配置,启动应用,访问http://localhost:8080/swagger-ui.html应该能够浏览接口说明列表,但是却报404错误。

再看看Springfox-swagger-ui的源码目录结构如下: 
SouthEast

SouthEast

SpringBoot官方文档显示:

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext。

所以springfox-swagger-ui里swagger-ui.html的目录是默认目录结构。 
显然两者的静态资源目录结构不一致,若项目首页能显示则swagger-ui不能显示,若swagger-ui页面能显示则首页不能显示。 

解决方案:

springmvc配置文件中添加

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

3.4结果

3eQNry2.jpg!web

3eQNry2.jpg!web


3.5注解说明:


@Api:用在类上,说明该类的作用

@ApiOperation:用在方法上,说明方法的作用,标注在具体请求上,value和notes的作用差不多,都是对请求进行说明;tags则是对请求进行分类的,比如你有好几个controller,分别属于不同的功能模块,那这里我们就可以使用tags来区分了,看上去很有条理

@ApiImplicitParams:用在方法上包含一组参数说明

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

paramType:参数放在哪个地方

header-->请求参数的获取:@RequestHeader

query-->请求参数的获取:@RequestParam

path(用于restful接口)-->请求参数的获取:@PathVariable

body(不常用)

form(不常用)

name:参数名

dataType:参数类型

required:参数是否必须传

value:参数的意思

defaultValue:参数的默认值

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

code:数字,例如400

message:信息,例如"请求参数没填好"

response:抛出异常的类

@ApiModel:描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)表明这是一个被swagger框架管理的model,用于class上

@ApiModelProperty 这里顾名思义,描述一个model的属性,就是标注在被标注了@ApiModel的class的属性上,这里的value是对字段的描述,example是取值例子,注意这里的example很有用,对于前后端开发工程师理解文档起到了关键的作用,因为会在api文档页面上显示出这些取值来;这个注解还有一些字段取值,可以自己研究,举例说一个:position,表明字段在model中的顺序


以上这些就是最常用的几个注解了。

猜你喜欢

转载自blog.csdn.net/Zhaky/article/details/64906686
今日推荐