背景
項目使用springmvc進(jìn)行設(shè)計,接口手動錄入yapi比較繁瑣;
查找資料通過swagger可以導(dǎo)入Postman及yapi;
所以決定試一下通過swagger2進(jìn)行接口文檔自動生成并導(dǎo)入yapi。
具體操作
步驟1:在pom.xml文件中添加如下依賴
<dependency>
? ? <groupId>io.springfox</groupId>
? ? <artifactId>springfox-swagger2</artifactId>
? ? <version>${swagger.version}</version>
</dependency>
<dependency>
? ? <groupId>io.springfox</groupId>
? ? <artifactId>springfox-swagger-ui</artifactId>
? ? <version>${swagger.version}</version>
</dependency>
<dependency>
其中${swagger.version}取值為2.2.2
步驟2.1:創(chuàng)建SwaggerConfig類,繼承自WebMvcConfigurerAdapter,并添加注解:
@Configuration
@EnableSwagger2
步驟2.2:創(chuàng)建Docket,通過其select返回的ApiSelectorBuilder下的apis方法,設(shè)置具體的接口文檔生成方式,覆蓋如下兩種:
方式1:只生成特定接口描述,通過在API對應(yīng)的方法上面添加注解@ApiOperation給API增加說明,通過@ApiImplicitParams、@ApiImplicitParam注解來給參數(shù)增加說明
方式2:特定包下所有接口描述,通過指定包名,添加在該包下所有controller層下API說明,統(tǒng)一使用默認(rèn)的說明方式生成文檔;如果需要修改相關(guān)描述,可以使用@ApiOperation等注解進(jìn)行說明
綜合步驟2的具體代碼如下(未貼出import相關(guān)代碼):
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
? ? @Override
? ? public void addResourceHandlers(ResourceHandlerRegistry registry) {
? ? ? ? registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
? ? ? ? registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
? ? }
? ? @Bean
? ? public Docket createRestApi() {
? ? ? ? return new Docket(DocumentationType.SWAGGER_2)
? ? ? ? ? ? .apiInfo(apiInfo())
? ? ? ? ? ? .select()
? ?.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))? //加了ApiOperation注解的方法,生成接口文檔? ? ? //.apis(RequestHandlerSelectors.basePackage("io.renren.modules.job.controller"))? //包下的類,生成接口文檔
? ? ? ? ? ? .paths(PathSelectors.any())
? ? ? ? ? ? .build();
? ? }
? ? private ApiInfo apiInfo() {
? ? ? ? return new ApiInfoBuilder()
? ? ? ? ? ? .title("標(biāo)題")
? ? ? ? ? ? .description("文檔描述")
? ? ? ? ? ? .termsOfServiceUrl("服務(wù)條款對應(yīng)的url")
? ? ? ? ? ? .version("1.3")
? ? ? ? ? ? .build();
? ? }
}
步驟3:編譯并啟動項目,通過http://ip:port/swagger-ui.html進(jìn)行查看,同時可以輸入接口參數(shù),手動執(zhí)行簡單的測試;
步驟4:進(jìn)入yapi的數(shù)據(jù)管理頁面,通過swagger方式,輸入swagger的json文件對應(yīng)的url:http://{ip}:{port}/{project Name}/v2/api-docs 執(zhí)行數(shù)據(jù)導(dǎo)入操作,如:http://127.0.0.1:8080/renren-fast/v2/api-docs
備注
關(guān)于yapi搭建,參見文章《docker-compose的方式搭建yapi》