Swagger是一个RESTFUL 接口的文档在线自动生成和功能测试的框架。利用swagger2的注解可以快速的在项目中构建Api接口文档,并且提供了测试API的功能。
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
@Configuration
@EnableSwagger2
public class Swagger2Configration {
/*
* 创建api文档
* */
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select() .apis(RequestHandlerSelectors.basePackage("com.jotal.springboot06swagger2.Controller")) //为该包下的类API文档
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//为有@Api注解的类生成API文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) //为有@ApiOperation注解的方法生成API文档
.paths(PathSelectors.any())
.build();
}
/*
* api文档展示信息
* */
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("Jotal项目接口文档")
.description("测试api文档")
.contact(new Contact("jotal","jotalngu.github.io",null))
.version("0.1")
.build();
}
}
@Configuration 标注该类为配置类
@EnableSwagger2 启用Swagger2
@Bean 将Docket的实例对象注入Spring ioc容器中
apis 为选择生成Api文档的范围,有三种方式:
- 生成指定包下面的类的API文档
- 生成有指定注解的类的API文档
- 生成有指定注解的方法的API文档
paths(PathSelectors.any()) 表示路径选择器匹配所有路径
package com.jotal.springboot06swagger2.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "用户信息")
public class User {
@ApiModelProperty(value ="年龄",name = "age")
private int age;
private String name;
//getter、setter、toString和构造器
}
package com.jotal.springboot06swagger2.Controller;
import com.jotal.springboot06swagger2.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/testApi")
@Api(tags = "用户信息接口")
public class UserController {
@GetMapping("/getAllUser")
@ApiOperation(value="查询所有", notes="查询所有用户信息")
public List<User> getAllUser(){
List<User> userList = new ArrayList<>();
for(int i=0;i<4;i++){
User user = new User();
user.setAge(i);
userList.add(user);
}
return userList;
}
}
http://localhost:8080/swagger-ui.html
点击Try it out! 就可以测试功能!
原文:https://www.cnblogs.com/Jotal/p/11317633.html