现如今,前后端分离已经逐渐成为互联网项目一种标准的开发方式,前端与后端交给不同的人员开发,
但是项目开发中的沟通成本也随之升高,这部分沟通成本主要在于前端开发人员与后端开发人员对WebAPI接口的沟通,Swagger2 就可以很好地解决,它可以动态生成Api接口文档,降低沟通成本,促进项目高效开发。
2.9.2
org.springframework.boot
spring-boot-starter-web
io.springfox
springfox-swagger2
${swagger.version}
io.springfox
springfox-swagger-ui
${swagger.version}
#生产环境改成false禁用
server:
port: 8017
swagger:
enable: true
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
* @return Docket
*/
@Bean(value = "defaultApi")
public Docket defaultApi() {
//添加header参数
ParameterBuilder ticketPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
ticketPar.name("token")
.description("用户登录获取的token信息")
.modelRef(new ModelRef("string")).parameterType("header")
//header中的参数是非必填的。
.required(false).build();
pars.add(ticketPar.build());
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
// 为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.ljm.boot.swagger"))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.groupName("需要token验证")
.globalOperationParameters(pars);
}
/**
* api文档的详细信息函数,注意这里的注解引用的是哪个
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// //大标题
.title("【SpringBoot框架篇】 17.swagger对接口文档进行管理")
// 版本号
.version("1.0")
.termsOfServiceUrl("NO terms of service")
// 描述
.description("本教程配套代码github地址:https://github.com/Dominick-Li/springboot-master")
//作者
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
常用注解
@ApiImplicitParam参数说明
属性 | 描述 |
---|---|
name | 参数名 |
value | 参数的描述信息 |
defaultValue | 默认值 |
required | 必选? (默认值false) ,设置true该参数必须填写 |
测试用例
@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
@GetMapping("/")
@ApiOperation("分页查询所有用户")
public List<User> getUserById(@RequestBody PageParam pageParam) {
return new ArrayList<User>();
}
@GetMapping("/{id}")
@ApiOperation("根据id查询用户的接口")
@ApiImplicitParam(name = "id", value = "用户id", required = true)
public User getUserById(@PathVariable Integer id) {
return new User();
}
@PostMapping("/")
@ApiOperation("添加用户的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "北京", required = true)
})
public HttpResult addUser(String username, @RequestParam(required = true) String address) {
return HttpResult.successResult();
}
@PutMapping("/{id}")
@ApiOperation("根据id更新用户的接口")
public HttpResult updateUserById(@RequestBody User user) {
return HttpResult.successResult();
}
}
常用注解
测试用例
@ApiModel("用户类")
public class User {
@ApiModelProperty("用户唯一id")
private Integer id;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("地址")
private String address;
//省略get set方法
}
@ApiModel("Http结果响应")
public class HttpResult implements Serializable {
private static String successMessage = "操作成功";
private static String errorMessage = "操作失败";
@ApiModelProperty("响应码")
private int code;
@ApiModelProperty("响应数据")
private Object data;
@ApiModelProperty("响应消息")
private String msg;
public HttpResult(){ }
public HttpResult(int code, String msg) {
this.code=code;
this.msg=msg;
}
public HttpResult(int code, String msg, Object data) {
this.code=code;
this.msg=msg;
this.data=data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static HttpResult successResult() {
return new HttpResult(HttpStatus.OK.value(), successMessage);
}
public static HttpResult successResult(String msg) {
return new HttpResult(HttpStatus.OK.value(), defaultSuccessMsg(msg));
}
public static HttpResult successResult(Object obj) {
return new HttpResult(HttpStatus.OK.value(), successMessage, obj);
}
public static HttpResult successResult(String msg, Object obj) {
return new HttpResult(HttpStatus.OK.value(), defaultSuccessMsg(msg), obj);
}
public static HttpResult failureResult() {
return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), errorMessage);
}
public static HttpResult failureResult(String msg) {
return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), defautlErrorMsg(msg));
}
public static HttpResult failureResult(Integer code, String msg) {
return new HttpResult(code, defautlErrorMsg(msg));
}
public static HttpResult failureResult(String msg, Object obj) {
return new HttpResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), defaultSuccessMsg(msg), obj);
}
private static String defautlErrorMsg(String msg) {
return StringUtils.isEmpty(msg)?errorMessage:msg;
}
private static String defaultSuccessMsg(String msg) {
return StringUtils.isEmpty(msg)?successMessage:msg;
}
}
访问http://localhost:8017/swagger-ui.html查看API接口文档
让类变成泛型类@ApiModel("Http结果响应")
public class HttpResult<T> implements Serializable {}
@ApiModelProperty("响应数据")
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@GetMapping("/{id}")
public HttpResult<User> getUserById(@PathVariable Integer id) {
return HttpResult.successResult(new User());
}
重新启动项目查看接口描述,看到data属性里已经变成了ApiModel类了。
github地址
创作不易,要是觉得我写的对你有点帮助的话,麻烦在github上帮我点下 Star
【SpringBoot框架篇】其它文章如下,后续会继续更新。