工作中使用Swagger生成接口文檔,但是隨著版本的迭代,總的接口數(shù)量越來越多,而每次版本新增的接口或者修改的接口都會生成到總的文檔中,而為了方便按照版本來查看,所以我們就使用Swagger的版本查找
一 定義注解ApiVersion:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiVersion {
/**
* 接口版本號(對應(yīng)swagger中的group)
* @return String[]
*/
String[] group();
}
二 定義一個(gè)版本號常量
public interface ApiVersionConstant {
/**
* 圖審系統(tǒng)手機(jī)app1.0.0版本
*/
String FAP_APP100 = "app1.0.0";
}
三 更改SwaggerConfig添加Docket(可以理解成一組swagger 接口的集合)浊服,并定義groupName,根據(jù)ApiVersion的group方法區(qū)分不同組(迭代)的接口,代碼如下:
@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
//默認(rèn)版本的接口api-docs分組
@Bean
public Docket vDefault(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.select()
.apis(RequestHandlerSelectors.basePackage("com.gysoft"))//controller路徑
.paths(PathSelectors.any())
.build();
}
//app1.0.0版本對外接口
@Bean
public Docket vApp100(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf())
.groupName(FAP_APP100)
.select()
.apis(input -> {
ApiVersion apiVersion = input.getHandlerMethod().getMethodAnnotation(ApiVersion.class);
if(apiVersion!=null&&Arrays.asList(apiVersion.group()).contains(FAP_APP100)){
return true;
}
return false;
})//controller路徑
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInf(){
return new ApiInfoBuilder()
.title("接口列表")
.termsOfServiceUrl("http://127.0.0.1:8080/swagger-ui.html")
.description("springmvc swagger 接口測試")
.version("1.0.0")
.build();
}
}
四 使用
@RestController
@RequestMapping("/document")
@Api(value = "資料文檔或者CAD圖紙", description = "資料文檔或者CAD圖紙")
public class DocumentController extends GyBasicSession {
private static final Logger logger = LoggerFactory.getLogger(DocumentController.class);
@ApiImplicitParams({@ApiImplicitParam(name = "page", value = "當(dāng)前頁數(shù)", dataType = "int", paramType = "path"),
@ApiImplicitParam(name = "pageSize", value = "每頁大小", dataType = "int", paramType = "path"),
@ApiImplicitParam(name = "projectId", value = "項(xiàng)目id", dataType = "string", paramType = "path"),
@ApiImplicitParam(name = "stageNum", value = "階段編號", dataType = "string", paramType = "path"),
@ApiImplicitParam(name = "type", value = "0資料(文檔);1cad圖紙", dataType = "int", paramType = "path"),
@ApiImplicitParam(name = "searchkey", value = "搜索關(guān)鍵字", dataType = "string", paramType = "query")})
@ApiOperation("分頁獲取資料文檔(CAD圖紙)列表數(shù)據(jù)")
@GetMapping("/pageQueryAppDocumentInfo/{page}/{pageSize}/{projectId}/{stageNum}/{type}")
@ApiVersion(group = ApiVersionConstant.FAP_APP100)
public PageResult<AppDocumentInfo> pageQueryAppDocumentInfo(@PathVariable Integer page, @PathVariable Integer pageSize, @PathVariable String projectId, @PathVariable String stageNum, @PathVariable Integer type, @RequestParam String searchkey) {
return null;
}
}
五 效果
image.png