Swagger与springMvc集成

深度截图_选择区域_20171205231637

Swagger是什么?官方的定义是:A POWERFUL INTERFACE TO YOUR API。简单来说,Swagger就是将后台提供的restful-api进行在前端展示并提供测试所用。

api文档的书写,就我个人而言,是极其难受的一件事情,首先你要将你所提供API的功能作用和使用方法向前端人员说明,不善言语的我是真的难以言表,Swagger正好解决了我的痛苦,我只需要通过在对应restful-api的方法上提供注解,Swagger就会通过一系列反射来动态生成一个.json文件,这个.json文件的信息就是restful-api的信息,然后通过前端js的解析展现json数据,转换成前端html页面所展示的数据。具体如下图所示:

深度截图_20171205225124

当我们用上Swagger之后,api文档的编写就变得异常简单,只需要通过几个注解功能就能够将api的具体功能与使用描述清楚

深度截图_选择区域_20171205225312

在生成Swagger前端api文档后,前端人员就可以通过直接表单提交进行测试数据提交的结果返回

深度截图_选择区域_20171205225510

可见,Swagger的出现,极大方便了前后端人员对于api的交接与数据格式的对接。(这只是我个人感觉,可能会有理解不当之处)。

但是,本文的重点是介绍如何将Swagger和spring-mvc进行结合起来的,那就开始吧。首先我们需要下载连个依赖包

1
2
3
4
5
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.2'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.2'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.2'

(我使用gradle来管理项目的,说实话,觉得maven的xml式管理我觉得太丑了)
下载好后,我们编写一个配置类:SwaggerConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Component
@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = "com.nblot.controller.*")
public class SwaggerConfig {

public SwaggerConfig() {
}

@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.useDefaultResponseMessages(false);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Api Documents")
.contact(new Contact("liaochuntao", "", "liaochunyhm@live.com"))
.build();
}
}

@Component是让这个类能被spring扫描到,从而是这个配置类能够起作用;
@Configuration是描述这个类是一个配置类;
@EnableSwagger2 是使swagger2生效;
@EnableWebMvc是启用spring-mvc相关java配置
@ComponentScan(basepackages=“”)是Swagger扫描提供restful-api接口的类,一般都是扫描带有requestMapping注解的类。

然后,我们再sprin-config.xml配置文件上加上这些信息

1
2
<mvc:default-servlet-handler/>;
<mvc:resources mapping="index.html" location="classpath:/swagger/**" />;

为了能够使用Swagger,我们需要使用spring-mvc的默认拦截,同时我们还需要避免
Swagger的静态资源被sprin-mvc拦截进而导致页面无法显示的异常情况。

在做完上述工作之后,我们就可以使用Swagger了。

那么如何描述restful-api信息呢?Swagger提供了丰富的注解功能让我们去描述一个restful-api接口的具体功能与使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@Api(description = "用户信息中心接口")
@RequestMapping(value = "/app")
@Controller
public class UserInfoController {

@Autowired
@Resource(name = "loginImpl")
private loginInterface loginImpl;

@Autowired
@Resource(name = "uploadImpl")
private multipartInterface uploadImpl;

@Autowired
@Resource(name = "sendAuthCodeImpl")
private sendauthInterface authCodeImpl;

/**
*
* @param jwtUser
* @return
*/
@ApiOperation(value = "Update User Info", notes = "更新用户信息,在url中带上用户 username(这不是账户)")
@ResponseBody
@RequestMapping(value = "/{username}/update/userInfo", method = RequestMethod.POST)
public String updateUserInfo(JwtUser jwtUser, @PathVariable String username) {
return (String) loginImpl.updata(jwtUser).getData();
}

/**
*
* @param jwtUser
* @param session
* @return
*/
@ApiOperation(value = "Get Auth Code", notes = "进行安全操作时必须获取短信验证码")
@ResponseBody
@RequestMapping(value = "/get/auth_code", method = RequestMethod.GET)
public String getSecurityAuthCode(@ModelAttribute JwtUser jwtUser, HttpSession session) {
return (String) authCodeImpl.sendCode(jwtUser, session).getData();
}

/**
*
* @param jwtUser
* @param authCode
* @param session
* @return
*/
@ApiOperation(value = "Modify User Password", notes = "用户更新账户密码")
@ResponseBody
@RequestMapping(value = "/update/modify/password", method = RequestMethod.POST)
public String ModifyUserPassword(@Validated JwtUser jwtUser, String authCode, HttpSession session) {
return (String) loginImpl.modifyPassword(authCode, jwtUser, session).getData();
}

/**
* 需要把错误信息返回至App端
* @param multipartFile
* @return
*/
@ApiOperation(value = "Upload Head Image", notes = "用户更新头像信息")
@ResponseBody
@RequestMapping(value = "/{username}/upload/head", method = RequestMethod.PUT)
public String uploadHeadImage(MultipartFile multipartFile, @PathVariable String username) {
uploadImpl.uploadMultipart(multipartFile);
return null;
}

}

@Api(description =“”)是用于描述这一个类的作用,相当于是一堆方法的老大描述
@ApiOperation 是用于描述一个接口的功能,相当于是对老大下面的小弟进行进一步描述
@ApiModel 是用于表单绑定数据的,这个是绑定一个类

1
2
3
4
5
6
7
8
9
10
@ApiModel(value = "User", description = "用户对象")
public class User {

@ApiModelProperty(value = "account")
protected String account;
@ApiModelProperty(value = "password")
protected String password;
protected int userId;
protected String token;
}

就像这样

@ApiModelProperty(value = “account”)是用于绑定表单的某一数据到对象的某一个属性

通过利用@ApiModel,@ApiModelProperty这两个注解我们就可以很方便的和spring-mvc的表单绑定相结合工作。

未完待续……;

(继续介绍Swagger的注解方法,以及springBoot和Swagger协同工作的配置)