springboot2.0 swagger2 生成离线文档

前面写了springboot swagger2生成在线文档,应公司要求,还必须生成离线文档,两个相结合,这个为什么要自动生成文档的缘由就不说了,想必大家心里都清楚

maven依赖


        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
    

    
        ${project.build.directory}/generated-snippets
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
        

        
            io.springfox
            springfox-swagger2
            2.6.1
        

        
            io.springfox
            springfox-swagger-ui
            2.6.1
        

        
            org.springframework.restdocs
            spring-restdocs-mockmvc
            test
        

        
            io.springfox
            springfox-staticdocs
            2.6.1
        

	    
			org.projectlombok
			lombok
			1.16.10
		

        
            com.alibaba
            fastjson
            1.2.8
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            

            
                org.apache.maven.plugins
                maven-surefire-plugin
                
                    
                        **/*Documentation.java
                    
                
            

          
        
    

代码部分

index.adoc文件

新建文件及目录结构 src/docs/asciidoc/index.adoc
内容如下

include::{generated}/overview.adoc[]
include::{generated}/definitions.adoc[]
include::{generated}/paths.adoc[]

swagger配置

import springfox.documentation.service.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            // 自己controller 路径
            .apis(RequestHandlerSelectors.basePackage("com.controller"))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("api 接口")
                .description("rest服务说明")
                .version("2.0").contact(new Contact("liu", "url", "[email protected]")).build();
    }

}

controller

import com.chinamobile.iot.model.Student;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api("HelloController 相关接口说明")
@ApiResponses({
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(code = 400, message = "客户端请求错误"),
        @ApiResponse(code = 404, message = "找不到路径"),
        @ApiResponse(code = 500, message = "编译异常")
})
public class HelloController {

    @ApiOperation(value = "查询某个设备信息", notes = "查询某个设备信息 1")
    @GetMapping("/getDevice/{id}")
    public String getDevice(@ApiParam(name = "id", value = "设备的唯一编号", required = true) @PathVariable int id,
                            @RequestBody Student student) {

        return "hello swagger2: "+ id;
    }
    
}

这个只是一个使用案例,还有很多注解
注意 @RequestBody Student student 纯粹是为了看实体类的效果加的,打包后在definitions.adoc文件中,当然了,还有其他方式,这只是一种

实体类

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@ApiModel(value = "Student", description = "学生信息描述")
@Data
public class Student {
    
    @ApiModelProperty("学号")
    private int id;
    
    @ApiModelProperty("姓名")
    private String name;
  
    @ApiModelProperty("年龄")
    private int age;
 
    @ApiModelProperty("性别")
    private String sex;

    @ApiModelProperty("班级")
    private String cls;
   
    @ApiModelProperty("家庭住址")
    private String address;
    
}

test 目录下的Documentation类


import io.github.robwin.markup.builder.MarkupLanguage;
import io.github.robwin.swagger2markup.GroupBy;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import springfox.documentation.staticdocs.SwaggerResultHandler;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@AutoConfigureMockMvc
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
@RunWith(SpringRunner.class)
@SpringBootTest
public class Documentation {

    private String snippetDir = "target/generated-snippets";
    private String outputDir = "target/asciidoc";
    //private String indexDoc = "docs/asciidoc/index.adoc";

    @Autowired
    private MockMvc mockMvc;

    @After
    public void test() throws Exception{
        // 得到swagger.json,写入outputDir目录中
        mockMvc.perform(RestDocumentationRequestBuilders.get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))
                .andDo(SwaggerResultHandler.outputDirectory(outputDir).build())
                .andExpect(status().isOk())
                .andReturn();

        // 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir
        // 这个outputDir必须和插件里面标签配置一致
        Swagger2MarkupConverter.from(outputDir + "/swagger.json")
                .withPathsGroupedBy(GroupBy.TAGS)// 按tag排序
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式
                .withExamples(snippetDir)
                .build()
                .intoFolder(outputDir);// 输出
    }

    @Test
    public void testApi() throws Exception{

    }
}

测试

打包即可
打包完成在target/asciidoc目录下就可以看文档

参考 https://www.jianshu.com/p/af7a6f29bf4f
注意,该博主的springboot版本是1.4.0的,如若用现在最新的2.0.5会报错,得把pom.xml修改一点点

你可能感兴趣的:(spring)