由于现在项目的趋势慢慢往前后端分离出发,所以维护接口文档基本是必不可少的工作。一个理想的状态是设计好好,接口文档发给前端和后端,大家按照既定的规则各自进行开发,开发完后之后就可以进行对接,紧接着上线。当然这是一个非常理想的状态,实际开发的过程中,接口总是在不断的变化中,有变化就需要去维护,做过具体的项目就知道有多头大!还好有工具可以减轻我们的工作量,Swagger2就是其中之一
1、基础环境搭建【快速开发】
接下来我们来了解SpringBoot框架如何整合Swagger开发接口文档
1、工程创建
通过Spring Inintailizr来创建好SpringBoot项目
2、导入相关依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3、配置Swagger2
在项目创建之后,只需要开发者自己提供一个Docket的Bean即可,所以我们提供一个配置类,首先通过@EnableSwagger注解启动Swagger2,然后@Configuration使得这个类可以被SpringBoot扫描到,然后配置一个Docket【Bean】,加到Spring容器中,在这个Bean中,配置映射路径和要扫描的接口的位置,在apiInfo中,主要配置一下Swagger2文档网站的信息,例如网站的title,网站的描述,联系人的信息,使用的协议等等…到这一步我们的Swagger算是配置成功了!
package com.chen.config;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.chen.controller")) //扫描指定的包
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.contact(new Contact("Czh啊哈","blog.csdn.net","2425540101@qq.com"))
.license("The Apache License")
.licenseUrl("http://www.baidu.com")
.build());
}
}
4、启动项目,在地址栏输入:http://localhost:8080/swagger-ui.html
2、创建接口
到这里我们就简单的配置好了Swagger所需的环境,接下来就是我们的重头戏创建接口,Swagger的相关注解并不是很多,而且比较通俗易懂,下面我来给小伙伴们举例说明:
1、UserControlelr类
@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
@PostMapping("/")
@ApiOperation("添加用户的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
}
)
public RespBean addUser(String username, @RequestParam(required = true) String address) {
return new RespBean();
}
@GetMapping("/")
@ApiOperation("根据id查询用户的接口")
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
public User getUserById(@PathVariable Integer id) {
User user = new User();
user.setId(id);
return user;
}
@PutMapping("/{id}")
@ApiOperation("根据id更新用户的接口")
public User updateUserById(@RequestBody User user) {
return user;
}
}
这里涉及到多个API,我们来逐一分析下
(1)@Api注解可以用来表级当前Controller的功能
(2)@ApiOperation注解用来标记一个方法的作用
(3)@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入
(4)如果有多个参数,则需要多个@ApiInlpicitParam注解来描述,放在一个@ApiInlpicitParams中
(5)需要注意的是,@ApiInlpicitParam注解中虽然可以指定参数是必填的,但是却不能代替@RequestParam(required= true),前者的必填知识在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以开发者如果假定一个参数必填,@RequestParam(required = true)注解还是不能省略
(6)如果参数是一个对象(例如上文的更新接口),对于参数的描述也可以放在实体类中,如下
@ApiModel
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户地址")
private String address;
//getter/setter
}
2、RespBean类
package com.chen.controller;
public class RespBean {
private String code = "200";
private String msg = "访问成功! ";
}
经过如上的配置,我们看下刷新之后的Swagger界面,可以看到如下效果!
可以看到所有的接口都列出来了,包括接口的请求方式,接口的地址以及接口的名字等
3、使用Swagger进行测试
4、拓展
如果我们在Springboot项目中集成了SpringSecurity,那么如果不做额外的配置,Swagger文档可能被拦截,此时只需要在SpringSecurity配置类中重写config方法,添加如下过滤即可:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/swagger-ui.html")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}
如此之后,Swagger2文件就不需要认证就可以访问了!