SpringBoot Swagger2 Response统一默认返回信息
SpringBoot 集成knife4j swagger2 统一默认Response
knife4j 文档 https://doc.xiaominfo.com/knife4j/documentation/
pom依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<!--在引用时请在maven*仓库搜索3.X最新版本号-->
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>xxx</version>
</dependency>
swagger配置文件
通过globalResponses来设置统一的Response返回业务编码
RequestHandlerSelectors.basePackage扫描路径
withMethodAnnotation(ApiOperation.class) 扫描有ApiOperation注解的方法
package com.dogs.doc.config;
import java.util.ArrayList;
import java.util.List;
import com.dogs.doc.enums.ResponseCodeEnums;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author: Rubble
* @date: 2021/5/18
**/
@Configuration
public class Swagger2Config {
@Bean
public Docket createRestApi() {
List<Response> globalResponses = new ArrayList<>();
for (ResponseCodeEnums item : ResponseCodeEnums.values()) {
globalResponses.add(new ResponseBuilder()
.code(String.valueOf(item.getCode()))
.description(item.getDesc())
.build());
}
return new Docket(DocumentationType.OAS_30)
.useDefaultResponseMessages(true)
.globalResponses(HttpMethod.GET, globalResponses)
.globalResponses(HttpMethod.POST, globalResponses)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dogs.doc.controller"))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Dogs APIs")
.description("knife4j")
.termsOfServiceUrl("http://www.baidu.com")
.version("3.0")
.build();
}
}
ResponseCodeEnums.java
package com.dogs.doc.enums;
import lombok.Getter;
/**
* @author: Rubble
* @date: 2021/5/18
**/
@Getter
public enum ResponseCodeEnums {
/**
* ResponseCodeEnums 返回业务编码
*/
CODE_500(500,"你是否还会在灯火下守候……"),
CODE_800001(800001,"测试业务编码800001"),
CODE_800002(800002,"测试业务编码800002");
int code;
String desc;
ResponseCodeEnums (int code, String desc) {
this.code = code;
this.desc = desc;
}
}
@ApiResponse 可以为每个接口指定特别的返回值,一般都放到Enum中
@RestController
public class DocController {
@ApiOperation("Response测试返回信息")
@ApiResponses({
@ApiResponse(code = 600100,message = "那个特别的你")
})
@GetMapping("/rep")
public Object apiResponse(){
return "rep";
}
}
doc文档显示
喜欢就扫码关注下吧