在项目开发中,我们经常需要进行前后端接口联调的工作,以往通过api接口文档进行接口的描述,一旦接口有什么改动,就需要进行api文档的更改,很不方便,现在我们可以通过swagger进行接口的在线查看和调用,非常方便,如果你对swagger不是很了解,请看这里:5分钟了解swagger 。
下面以springboot为例,进行swagger的配置使用说明,具体如下:
1、引入pom
<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>
2、swagger配置
/**
* @ClassName: SwaggerConfig
* @Description: swagger配置
* @author ejshi
* @date 2018年1月31日 下午7:53:38
*/
@SpringBootConfiguration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("org.regulus.account.consumer.controller"))
.paths(PathSelectors.any())
// .paths(Predicates.or(PathSelectors.regex("/[api|demo]/.*")))//过滤的接口
.build();
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("Api Documentation")
.description("Api Documentation")
.version("1.0.0")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.contact(new Contact("shijun", "https://swagger.io/", "gsshijun@126.com"))
.build();
}
}
3、controller接口类中使用swagger
@Api(value= "UserController",tags ="用户管理" ,description="用户管理相关功能API")
@RestController
public class UserController {
@Reference
private UserProvider userProvider;
@ApiOperation(value = "新增" ,notes="新增数据记录")
@PostMapping(path = "/user/add")
public ResponseJson<Object> addUser(
@ApiParam("请求参数") @RequestBody @Validated(UserRequest.Add.class) UserRequest userRequest){
User user = BeanCopierUtil.invoke(userRequest, User.class);
user.setId(StringUtil.uuid());
userProvider.insertSelective(user);
return new ResponseJson<Object>(true, ResponseCodeEnum.SUCCESS);
}
@ApiOperation(value = "查询" ,notes="查询相应数据记录,分页显示")
@GetMapping(path = "/user/listPage")
public ResponseJson<List<UserResponse>> listPageUser(@ApiParam("请求数据") UserQuery userQuery){
User user = BeanCopierUtil.invoke(userQuery, User.class);
PageResultModel<User> pageResult = userProvider.selectWithPage(user, userQuery.getPageNum(), userQuery.getPageSize());
List<UserResponse> userResponses = BeanCopierUtil.invokeList(pageResult.getDataList(), UserResponse.class);
return new ResponseJson<List<UserResponse>>(true, ResponseCodeEnum.SUCCESS, userResponses,pageResult.getTotal());
}
}
4、请求参数类,如UserQuery中使用swagger注解
@ApiModel
public class UserQuery {
private static final long serialVersionUID = -2840366087876556526L;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("用户状态")
private String userStatus;
//省略get/set方法
}
5、swagger在线api如图所示
6、简单swagger注解参数讲解
注解 | 常见用法 |
@Api | 用于controller类上 |
@ApiOperation | 用于controller中的接口方法上 |
@ApiParam | 用于请求参数 |
@ApiModel | 用于请求或者响应类上,如UserQuery |
@ApiModelProperty | 用于@ApiModel注解类中的属性上 |
7、查看swagger注解的使用说明,点击这里,或这里swagger官网