2019年5月22日记
需求:前端需要一份接口文档,进行接口联调。接口经常变动,所以需要重新编辑接口doc文档,发送给前端。十分不方便,基于此我们引入swagger,让我们更好的写API文档,还可以完全模拟http请求。
废话不多说,先让代码(很简单)跑起来。看效果
代码的地址:https://gitee.com/tcyj/SpringbootSwaggerDemo.git
1、具体步骤
1.1、配置pom.xml
<parent>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-parent
</artifactId>
<version>2.0.1.RELEASE
</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-web
</artifactId>
</dependency>
<dependency>
<groupId>com.spring4all
</groupId>
<artifactId>swagger-spring-boot-starter
</artifactId>
<version>1.7.0.RELEASE
</version>
</dependency>
</dependencies>
</project>
1.2、配置controller类
package com
.swagger
.controller
;
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 io
.swagger
.annotations
.Api
;
import io
.swagger
.annotations
.ApiOperation
;
@Api(tags
= "用户接口")
@RestController
@RequestMapping("/swaggerController")
public class SwaggerController {
@ApiOperation(value
= "新增用户")
@RequestMapping(value
="/createUser",method
=RequestMethod
.POST
)
public Object
createUser(){
return "新增成功";
}
@ApiOperation(value
= "修改用户")
@RequestMapping(value
="/updateUser",method
=RequestMethod
.POST
)
public Object
updateUser(){
return "修改成功";
}
@ApiOperation(value
= "删除用户")
@RequestMapping(value
="/deleteUser",method
=RequestMethod
.DELETE
)
public Object
deleteUser(@RequestParam("userId") String userId
){
return "删除成功";
}
}
1.3、配置app启动类
package com
.swagger
;
import org
.springframework
.boot
.SpringApplication
;
import org
.springframework
.boot
.autoconfigure
.SpringBootApplication
;
import com
.spring4all
.swagger
.EnableSwagger2Doc
;
@SpringBootApplication
@EnableSwagger2Doc
public class AppSwagger {
public static void main(String
[] args
) {
SpringApplication
.run(AppSwagger
.class, args
);
}
}
1.4、配置application.yml
server:
port: 8300
spring:
application:
name: app
-swagger
swagger:
base-package: com.swagger
title: 用户服务接口
description:
version: 1.1
terms-of-service-url: www.demoswagger.com
contact:
name: 柯俊
email: 2308517778@qq.com
2、效果展示
2.1、启动启动类之后访问:http://localhost:8300/swagger-ui.html
2.2、点击try it out 按钮
2.3、输入接口的具体参数
2.4、点击execute,接口调通。看下面Response body,返回值
如果是2个项目,一个是接口工程一个是实现工程,要用swagger生成接口
参考代码入:
接口工程实现工程
https://gitee.com/tcyj/SpringbootSwaggerInterface.githttps://gitee.com/tcyj/SpringbootSwaggerImpl.git
如果是带有网关做统一的接口文档处理,参考代码如下:
https://gitee.com/tcyj/swagger-parent.git
更多请参考资料:https://blog.csdn.net/itguangit/article/details/78978296