Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 Restfull 风格的 Web 接口服务,在当前前后端分离的情况下,利用swagger搭建一个接口服务平台,接口服务平台可以减少一些前后台的不必要沟通,前端只需要根据接口便可以进行前端开发。
这里swagger是在现有的一个springboot jpa工程上进行改造,现有的工程可以正常访问,在此基础上进行改造。
下面一步步介绍下改造过程。
1、添加swagger依赖
在工程pom.xml文件中引入依赖,包括springfox-swagger2 和 springfox-swagger-ui 的依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2、配置swagger2
写一个配置类swagger2,在类的上方增加@Configuration注解,标注该类是一个配置类,增加@EnableSwagger2注解,开启swagger2的功能。在配置类swagger2中需要注入一个Docket的Bean,该Bean包含了api,即基本API的描述信息,以及包含描述的基本包名等信息。
package com.swagger.sw;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
@Configuration
@EnableSwagger2
public class Swagger2 {
/**
* 需要生成接口的包路径
*/
public static String packagePath = "com.swagger.jpa.controller";
/**
* 创建rest风格API
* @return
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(packagePath))
.paths(PathSelectors.any())
.build();
}
/**
* API具体信息内容
* @return
*/
private ApiInfo apiInfo() {
// API作者信息
Contact contact = new Contact("姜小白", "blog.csdn.net/magi1201", "[email protected]");
return new ApiInfoBuilder()
.title("springboot jpa项目API文档")
.description("jpa项目接口文档")
.termsOfServiceUrl("http://localhost:8080/user")
.version("1.0")
.contact(contact)
.build();
}
}
上面我们给com.swagger.jpa.controller 路径下面的类生成接口文档
3、写生成文档的注解
swagger2通过注解来生成API接口文档,文档信息包括接口名、请求方法、参数、返回信息等。
swagger常用的注解有下面

- @Api:修饰整个类,用于描述Controller类
- @ApiOperation:描述类的方法,或者接口
- @ApiParam:单个参数描述
- @ApiModel:用对象来接收参数
- @ApiProperty:用对象接收参数时,描述对象的一个字段
- @ApiResponse:HTTP响应的一个描述
- @ApiResponses:HTTP响应的整体描述
- @ApiIgnore:忽略该API,该注解修饰的组件不生成接口文档
- @ApiError:发生错误时返回的信息
- @ApiParamImplicit:一个请求参数
- @ApiParamsImplict:多个请求参数
4、 改写Controller层
对Controller层涉及到的接口和方法及实体类进行改造,改造为可以生成接口文档的格式。
@Api(value = "用户管理控制层")
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService us;
@ApiOperation(value = "获取用户信息", notes = "根据用户姓名获取用户信息")
@RequestMapping(value = "/s/{username}", method = RequestMethod.GET)
public User getUser(@PathVariable("username")
@ApiParam(name = "username", required = true) String username) {
return us.getUser(username);
}
@ApiOperation(value = "获取用户信息", notes = "根据用户姓名获取用户信息")
@RequestMapping(value = "/i/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable("id")
@ApiParam(name = "id", required = true) Integer id) {
return us.findUserById(id);
}
@ApiOperation(value = "保存用户信息", notes = "保存用户信息")
@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public User saveUser(
@RequestBody @ApiParam(name = "user", value = "json fromat", required = true) User user) {
return us.saveUser(user);
}
@ApiOperation(value = "获取用户信息", notes = "获取所有用户信息")
@RequestMapping(value = "/getusers", method = RequestMethod.GET)
public List<User> getUsers() {
return us.findAllUsers();
}
@ApiOperation(value = "更新用户信息", notes = "更新用户信息")
@RequestMapping(value = "/upduser", method = RequestMethod.PUT)
public User updateUser(
@RequestBody @ApiParam(name = "user", value = "json fromat", required = true) User user) {
return us.updateUser(user);
}
@ApiOperation(value = "删除用户信息", notes = "根据用户ID删除用户信息")
@RequestMapping(value="/deluser", method = RequestMethod.DELETE)
public void deleteUserById(@RequestParam("id")
@ApiParam(name = "id", required = true) Integer id) {
us.deleteUserById(id);
}
@ApiIgnore
@RequestMapping(value="/hi")
public String testApi() {
return "This is a test Api";
}
}
至此,系统改造结束。
测试
启动工程,在浏览器输入 http://localhost:8080/swagger-ui.html#/ 可以看到
在此,可以看到Controller层定义的接口均展示在了接口文档中,并可以进行测试
点开 delete /user/deluser 删除用户信息
可以看到,方法信息主要包含三部分,
1 是接口参数,这里的参数是Integer型的id
2 是Try it out ,测试接口的操作区
3 Respouses , 操作返回区,这里定义了各种返回码和其含义的描述
点击 Try it out
tab页里面主要包含4部分
1、方法需要的参数
2、参数取消按钮,点击后会进入参数编辑状态,编辑状态时
3、执行execute按钮
4、取消测试按钮
参数输入3,点击execute按钮,执行delete操作
点击后,若成功,会看到响应端生成的请求url 和 服务器响应code,这里是200表示成功;若失败,则需要根据失败码及错误提示信息,查找错误原因。
其它方法的测试与deluser类似,这里就不再花篇幅介绍了,以上就是关于swagger的简单示例了,供学习参考。