作为一位Java码农,在web前后端分离项目开发中我认为写的最多的就是接口Api,大家各自约定好规则进行开发,前端只负责前端实现,后端负责提供数据接口,作为后端每当写完接口还得为前端小姐姐提供好接口文档以便他渲染数据,可过程却总是没有想象中美好,由于产品爸爸的需求不停的更改,使得我的接口也在不停的变,那么接口文档便也得跟着改,不仅如此前端小姐姐还总是抱怨我的文档更新不够及时,请求参数以及响应结果也不够明细,本文提到的Swaager2就很好的解决了我们的痛点。
什么是Swagger2
Swagger2 可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。常用注解swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
新建工程
首先新建一个SpringBoot工程引入web依赖,再加入今天的主角swagger依赖
<!--集成swagger以及UI-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
创建UserController接口类,以及Swagger2配置类
Swagger类:
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.java134.demo"))//包的根路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springBoot整合swagger")//接口文档标题设置
.description("项目所有API接口列表,www.java134.com")//描述
.version("1.0")//版本号
.build();
}
UserController类:
@Api("UserControllerApi列表")
@RestController
public class UserController {
@ApiOperation(value = "查询所有信息",notes = "查询数据库中某个学生的信息")
@GetMapping(value = "/queryAll")
public List<String> queryAll() throws Exception {
List<String> data=new ArrayList<String>();
data.add("java134");
data.add("java资料社区");
return data;
}
@ApiOperation(value="获取redis中数据", notes="通过key值获取")
@ApiResponses({
@ApiResponse(code=400,message = "请求报文存在语法错误"),
@ApiResponse(code=401,message = "发送的请求需要有通过 HTTP 认证的认证信息"),
@ApiResponse(code=403,message = "请求资源的访问被服务器拒绝"),
@ApiResponse(code=404,message="服务器上没有找到请求的资源")
})
@ApiImplicitParam(name = "key", value = "redis键值", required = true, dataType = "String")
@PostMapping(value = "/getRedis")
public String getRedis(String key) throws Exception {
Map<String,String> data=new HashMap<String,String>();
data.put("123","Java资料社区");
data.put("321","Java");
data.put("132","小编");
return data.get(key);
}
@ApiIgnore
@RequestMapping("/index")
public String index() {
return "ApiIgnore=忽略这个接口";
}
}
最后在SpringBoot启动类中加入@EnbleSwagger2注解,先启动项目看效果
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
访问:http://localhost:8080/swagger-ui.html 看到如下效果
可以看到Swagger为我们提供了一套很漂亮的可视化UI,我们UserController类中所有的方法都在这整齐的列出来,不仅如此,我们点开指定的接口还能实现在线测试,测试时对该接口的描述以及参数类型、根据不同状态码分别会响应什么话术描述的很清楚.
回过头来我们看看UserController加入的一些新注解,下面是Swagger2常用注解分别对应的效果.
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数