swagger2实战

swagger2实战

一、概论

服务器提供的java服务越来越多,每个服务提供的接口的文档化和自动化可以省略很多不必要的功夫。swagger2提供了这个能力。

二、在线api

swagger2通过在各Controller控制层加注解的方式,获取对每个接口的输入输出格式和http请求格式,整理成接口,前端 swagger-ui解析该接口数据并展示,还提供了对接口的测试功能。

1)  包依赖

根据不同jdk可适当降低版本。

<!--swagger2-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

2)  swaggerConfig类配置

注册进spring,并获取springMVC的接口信息。

@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("v1")
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.ant("/api/v1/**"))
                .build()
                .enableUrlTemplating(false);
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("使用Swagger2构建RESTful APIs")
                .description("本人期待更多的技术碰撞!请关注:[email protected]")
                .termsOfServiceUrl("[email protected]")
                .contact("wangjian")
                .version("1.0")
                .build();
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

3)  controller配置

各类注解,如@Api在类名上,@ApiOperation在方法上,描述接口的输入输出,点击参考链接

@Api(value="areaController",description = "区域")
@RestController
@Scope("prototype")
@RequestMapping("/api/v1/area")
public class AreaController extends BasicController<AreaService,AreaVO> {
   @ApiOperation(value = "获取区域分页列表",notes = "根据类型和页码")
   @ApiImplicitParams({
         @ApiImplicitParam (name="pageNum",value="页码",paramType = "path",required=true,dataType="Long"),
         @ApiImplicitParam (name="pageSize",value="单页数量",paramType = "path",required=true,dataType="Long"),
         @ApiImplicitParam (name="type",value="区域类型",paramType = "query",required=true,dataType="Long"),
         @ApiImplicitParam (name="name",value="搜索关键字",paramType = "query",required=true,dataType="Long")
   })
   @RequestMapping(value="select/{pageNum}/{pageSize}",method=RequestMethod.GET)
   public Result selectByPage(@PathVariable Long pageNum,@PathVariable Long pageSize,Long type,String name){
      return new Result(getService().selectListByPage(pageNum,pageSize,type,name));
   }
}

4)  swagger-ui配置

在springMVC的dispatchServlet 的url匹配是/时,不需要这一步,直接访问地址http://localhost/app/swagger-ui.html#/  即可。

而的url匹配不是/得情况下,需在前端直接存在页面和js。

修改index.html中36行的url为 url = "/app/v2/api-docs.mvc?group=v1";

这时打开http://localhos/app/{swagger2-Path}/swagger2/index.html 即可

{swagger2-Path}为swagger2前端包在所路径

三、离线api

在线api更多的是面向工程师,而不是第三方厂商,这时需要提供离线文档和SDK。swagger2markup是个开源jar包,可以将swagger2提供的接口数据转为常用的html或pdf或word离线文档。有两种方式,一个是java代码实现,一个是maven配置自动实现,这里只展示java实现。

1)  包依赖

必须jdk1.7以上才支持。

<!--swagger2markup-->
<dependency>
   <groupId>io.github.swagger2markup</groupId>
   <artifactId>swagger2markup</artifactId>
   <version>1.3.1</version>
</dependency>
<!--ascii转化为html/pdf-->
<dependency>
   <groupId>org.asciidoctor</groupId>
   <artifactId>asciidoctorj</artifactId>
   <version>1.5.6</version>
</dependency>
<dependency>
   <groupId>org.asciidoctor</groupId>
   <artifactId>asciidoctorj-pdf</artifactId>
   <version>1.5.0-alpha.16</version>
</dependency>

repositories里需要增加库地址

<repository>
   <id>jcenter-realses</id>
   <name>jcenter</name>
   <url>http://jcenter.bintray.com</url>
   <snapshots>
      <enabled>false</enabled>
   </snapshots>
</repository>

beanutils需要升级到1.9.3

<dependency>
   <groupId>commons-beanutils</groupId>
   <artifactId>commons-beanutils</artifactId>
   <version>1.9.3</version>
</dependency>

2)  转化为ascii.adoc文件

3)  将ascii.adoc转为html5或pdf

代码如下,根据不同服务,更改SWAGGER_URLDES_FILE_PATH即可。在DES_FILE_PATH会有.adoc和.html和.pdf三个文件。

import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import org.asciidoctor.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
/**
 * Created by 31261 on 2018/5/22.
 */
public class SwaggerTest {
    public static void main(String[] args) throws IOException {
        String SWAGGER_URL = "http://127.0.0.1:9080//app/v2/api-docs.mvc?group=v1";//查询的swagger2 json接口
        String DES_FILE_PATH = "d://del_file/docs";//下载到目标文件路径
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withPathsGroupedBy(GroupBy.TAGS)
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .build();//asscii转换配置
        Swagger2MarkupConverter
                .from(new URL(SWAGGER_URL))
                .withConfig(config)
                .build().toFile(Paths.get(DES_FILE_PATH+"/asciidoc"));//下载asciidoc.adoc文件
        //.adoc文件转化为html5
        Asciidoctor asciidoctor = Asciidoctor.Factory.create();
        Attributes attributes = new Attributes();
        attributes.setCopyCss(true);
        attributes.setLinkCss(false);
        attributes.setSectNumLevels(3);
        attributes.setAnchors(true);
        attributes.setSectionNumbers(true);
        attributes.setTableOfContents(Placement.LEFT);
        attributes.setAttribute("generated",DES_FILE_PATH+"/html");
        OptionsBuilder optionsBuilder = OptionsBuilder.options()
                .backend("html5")
                .docType("book")
                .eruby("")
                .inPlace(true)
                .safe(SafeMode.UNSAFE)
                .attributes(attributes);
        asciidoctor.convertFile(new          File(DES_FILE_PATH+"/asciidoc.adoc"),optionsBuilder.get());
        //.adoc文件转化为pdf
        attributes.setAttribute("generated",DES_FILE_PATH+"/pdf");
        optionsBuilder.backend("pdf").attributes(attributes);
        asciidoctor.convertFile(new File(DES_FILE_PATH+"/asciidoc.adoc"),optionsBuilder.get());
    }
}

 

 

猜你喜欢

转载自blog.csdn.net/qq_26409257/article/details/81539136