官方文档:
 
swagger是一个前后端api统一文档和测试框架,注意,不光是一个api文档,还可以测试
 
  • 怎么使用呢 这里慢慢道来,我们一般用的都是maven工程,所以这里直接上maven依赖
<swagger.version>1.5.8</swagger.version>
<io.springfox.version>2.5.0</io.springfox.version>
<!-- swagger start -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox.version}</version>
</dependency>
<!-- swagger end -->
 
  • 这里我们需要注入SwaggerConfiguration配置,直接上代码
/**
* Created by max on 8/16/16.
*
*/
@EnableSwagger2
public class SwaggerConfiguration { @Bean
public Docket getApiInfo() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("outer api")
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(outApiInfo()); } private ApiInfo outApiInfo() {
return new ApiInfo(
"mylearn 前后端接口-外部", // title 标题
"外部接口文档", // description 描述 标题下
"1.0.0", // version
"http://mylearn/*", // termsOfService
new Contact("xieyuebin","","xieyuebin@meituan.com"), // contact
"Apache 2.0", // licence
"http://www.apache.org/licenses/LICENSE-2.0.html" // licence url
); } @Bean
public UiConfiguration getUiConfig() {
return new UiConfiguration(
null,// url,暂不用
"none", // docExpansion => none | list
"alpha", // apiSorter => alpha
"schema", // defaultModelRendering => schema
UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
false, // enableJsonEditor => true | false
true); // showRequestHeaders => true | false
}
这是对于文档的说明以及ui的一些配置
 
  • 然后我们还需要把swagger和spring mvc结合起来,首先在web.xml里加入swagger文档的访问路径:
<!-- swagger ui 的静态资源交由default处理-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/swagger-ui.html</url-pattern>
</servlet-mapping>
 
  • 然后我们在dispatch-servlet.xml里加入对swagger静态资源jar包的访问路径如下:
<!-- swagger 配置 ,线上版本需要注释掉 -->
<beans:bean class="com.meituan.maxtse.mylearn.swagger.SwaggerConfiguration"/>
<!-- swagger ui resources-->
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars"/>
这里我们用到了我们前面定义的SwaggerConfiguration类
  • 然后我们在controller和请求参数和返回参数里加入swagger提供的注解,直接上例子
入参:
/**
* Created by max on 10/11/16.
*/
@ApiModel(description = "用户请求表单")
public class UserForm { @ApiModelProperty(value = "姓名", example = "maxTse",position = 1)
private String username; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} @Override
public String toString() {
return "UserForm{" +
"username='" + username + '\'' +
'}';
}
}
返回值:
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel
public class OutResult<T> implements Serializable { @ApiModelProperty(value = "数据", example = "")
public T data; @ApiModelProperty(value = "状态码,0表示成功 其他表示失败", example = "0")
public int status; @ApiModelProperty(value = "错误信息", example = "操作成功")
public String message = "";
controller:
/**
* Created by max on 8/16/16.
*/
@Controller
@RequestMapping(value = "/test", consumes = "application/json", produces = "application/json")
public class TestController { private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @ApiOperation(value = "swagger test", notes = "swagger test first", tags = {SwaggerConstants.TEST_TAG})
@ResponseBody
@RequestMapping(value = "/first", method = RequestMethod.POST)
public OutResult<String> first(@RequestBody UserForm userForm) {
LOGGER.info("first userForm={}", userForm);
throw new RuntimeException("dd");
/*
return OutResult.successResult(userForm.getUsername());
*/
}
这里挨个注解解释下:
@ApiModel 表明这是一个被swagger框架管理的model,用于class上
@ApiModelProperty 这里顾名思义,就是标注在被标注了@ApiModel的class的属性上,
这里的value是对字段的描述,example是取值例子,注意这里的example很有用,对于前后端开发工程师理解文档起到了关键的作用,因为会在api文档页面上显示出这些取值来;这个注解还有一些字段取值,可以自己研究,举例说一个:position,表明字段在model中的顺序
@ApiOperation标注在具体请求上,value和notes的作用差不多,都是对请求进行说明;tags则是对请求进行分类的,比如你有好几个controller,分别属于不同的功能模块,那这里我们就可以使用tags来区分了,看上去很有条理
  • 下面我们启动项目,然后通过url:localhost:8080/swagger-ui.html来访问,就可以看到swagger文档界面了
这里是请求和返回结果的界面,看到这个界面是不是对刚才我们贴出来的具体例子里的注解上的每个值有所了解了,一一对应便能了解他们的作用
我们开始说了,这个不仅可以当文档使,而且还可以进行测试,没错,看看参数界面大家都知道了,实际上参数界面就在请求和返回结果的下面:
 
看到右上方的大红框,就是我们的入参格式,注意,这里是json格式的
然后我们可以在具体填入自己的请求参数后,点击下方的try it out按钮,就可以进行测试了。
总结:
使用swagger2.0框架大概这么几步:
1.添加maven依赖
2.编写SwaggerConfiguration配置
3.web.xml里添加swagger文档的访问路径,是静态资源
4.添加相关的spring mvc配置
5.在请求的入参和返回值 以及具体的请求上添加相应的注解
6.启动项目,访问swagger.html
注意:
由于这里使用的是json格式的入参和返回值,那么我们在controller的请求参数那里要加上@RequestBody注解,并且请求方法必须是post
 
 
 

swagger2.0与spring结合的更多相关文章

  1. Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(二)

    在上一篇文章中我详细的介绍了如何搭建maven环境以及生成一个maven骨架的web项目,那么这章中我将讲述Spring MVC的流程结构,Spring MVC与Struts2的区别,以及例子中的一些 ...

  2. Tomcat 6.0.32 +Spring dbcp datasource关闭Tomcat出现严重异常

    异常如下: 信息: Pausing Coyote HTTP/ -- :: org.apache.catalina.core.StandardService stop 信息: Stopping serv ...

  3. spring boot 2.0.3+spring cloud (Finchley)3、声明式调用Feign

    Feign受Retrofix.JAXRS-2.0和WebSocket影响,采用了声明式API接口的风格,将Java Http客户端绑定到他的内部.Feign的首要目标是将Java Http客户端调用过 ...

  4. spring boot 2.0.3+spring cloud (Finchley)2、搭建负载均衡Ribbon (Eureka+Ribbon+RestTemplate)

    Ribbon是Netflix公司开源的一个负载均衡组件,将负载均衡逻辑封装在客户端中,运行在客户端的进程里. 本例子是在搭建好eureka的基础上进行的,可参考spring boot 2.0.3+sp ...

  5. spring boot 2.0.3+spring cloud (Finchley)8、微服务监控Spring Boot Admin

    参考:Spring Boot Admin 2.0 上手 Spring Boot Admin 用于管理和监控一个或多个Spring Boot程序,在 Spring Boot Actuator 的基础上提 ...

  6. spring boot 2.0.3+spring cloud (Finchley)5、路由网关Spring Cloud Zuul

    Zuul作为微服务系统的网关组件,用于构建边界服务,致力于动态路由.过滤.监控.弹性伸缩和安全. 为什么需要Zuul Zuul.Ribbon以及Eureka结合可以实现智能路由和负载均衡的功能:网关将 ...

  7. spring boot 2.0.3+spring cloud (Finchley)4、熔断器Hystrix

    在分布式系统中服务与服务之间的依赖错综复杂,一种不可避免的情况就是某些服务会出现故障,导致依赖于他们的其他服务出现远程调度的线程阻塞.某个服务的单个点的请求故障会导致用户的请求处于阻塞状态,最终的结果 ...

  8. 【Rocket MQ】RocketMQ4.2.0 和 spring boot的结合使用,实现分布式事务

    RocketMQ4.2.0 和 spring boot的结合使用,实现分布式事务 参考地址:https://www.jianshu.com/p/f57de40621a0

  9. 0、Spring 注解驱动开发

    0.Spring注解驱动开发 0.1 简介 <Spring注解驱动开发>是一套帮助我们深入了解Spring原理机制的教程: 现今SpringBoot.SpringCloud技术非常火热,作 ...

随机推荐

  1. elementUI table宽度自适应fit

    :fit='true' 或者直接为 fit

  2. hive数据库导入与导出

    原文连接:https://www.cnblogs.com/654wangzai321/p/9970321.html 把Hive表数据导入到本地 table->local file insert ...

  3. 小程序中为什么使用var that=this

    前言: 在小程序或者js开发中,经常需要使用var that = this;开始我以为是无用功,(原谅我的无知),后来从面向对象的角度一想就明白了,下面简单解释一下我自己的理解,欢迎指正批评. 代码示 ...

  4. vector<类指针>清理

    https://www.cnblogs.com/nanke/archive/2011/05/10/2042662.html 1.vector<class> &aa,作为函数参数 2 ...

  5. python-django_rest_framework中的request/Response

    rest_framework中的request是被rest_framework再次封装过的,并在原request上添加了许多别的属性: (原Django中的request可用request._requ ...

  6. 错误描述:fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h"”?(转)

    错误分析: 此错误发生的原因是编译器在寻找预编译指示头文件(默认#include "stdafx.h")时,文件未预期结束.没有找到预编译指示信息的头文件"stdafx. ...

  7. webpack 学习4 使用loader 以及常用的一些loader

    webpack本身只支持处理JavaScript,其他的文件,如css img less是不识别的,所以才会有loader这个东西,它就是可以使webpack能够处理其他非js文件的拓展程序 首先我们 ...

  8. webpack 学习1 安装构建项目

    本文中使用的webpack版本是4+,请注意区分 node.js安装 node.js下载地址 选择较低版本的稳定版下载,下载完成后得到的是一个msi文件,点击安装即可 安装完毕以后新建一个文件夹,并在 ...

  9. WGCNA构建基因共表达网络详细教程

    这篇文章更多的是对于混乱的中文资源的梳理,并补充了一些没有提到的重要参数,希望大家不会踩坑. 1. 简介 1.1 背景 WGCNA(weighted gene co-expression networ ...

  10. 【LeetCode 32】最长有效括号

    题目链接 [题解] 设dp[i]表示以第i个字符结尾的最长有效括号的长度. 显然只要考虑s[i]==')'的情况 则如果s[i-1]=='(',则dp[i] = dp[i-2]+2; 如果s[i-1] ...