hi,你好!欢迎访问本站!登录
本站由简数采集腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - 教程 - 杂谈 - 正文 君子好学,自强不息!

Spring Boot 2.X(十五):集成 Swagger2 开辟 API 文档(在线+离线)

2019-11-18杂谈搜奇网40°c
A+ A-

媒介

置信许多后端开发在项目中都邑遇到要写 api 文档,不管是给前端、挪动端等供应更好的对接,照样今后为了今后交代轻易,都邑要求写 api 文档。

而手写 api 文档的话有诸多痛点:

  • 文档更新的时刻,须要再次发送给对接人
  • 接口太对,手写文档很难治理
  • 接口返回的效果不明确
  • 不能直接在线测试接口,一般须要运用东西,如 postman 等

Swagger 就很好的处理了这个题目。

Swagger 简介

Swagger 是一个范例和完全的框架,用于生成、形貌、挪用和可视化 RESTful 作风的 Web 效劳。总体目标是使客户端和文件体系作为效劳器以一样的速率来更新。文件的要领,参数和模子严密集成到效劳器端的代码,许可API来始终保持同步。

官网:https://swagger.io

Swagger 运用

1.相干依靠

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

2.Swagger 设置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(buildApiInf()) //将api的元信息设置为包括在json resourcelisting响应中
        //.host("127.0.0.1:8080") //设置ip和端口,或许域名
        .select()  //启动用于api挑选的生成器
        //.apis(RequestHandlerSelectors.any())
        .apis(RequestHandlerSelectors.basePackage("cn.zwqh.springboot.controller"))//指定controller途径
        .paths(PathSelectors.any()).build();
    }

    private ApiInfo buildApiInf() {
        
        Contact contact=new Contact("朝雾轻寒","https://www.zwqh.top/","zwqh@clover1314.com");
        return new ApiInfoBuilder()
        .title("Swagger Demo Restful API Docs")//文档题目
        .description("Swagger 示例 Restful Api 文档")//文档形貌
        .contact(contact)//联系人
        .version("1.0")//版本号
        //.license("")//更新此API的许可证信息
        //.licenseUrl("")//更新此API的许可证Url
        //.termsOfServiceUrl("")//更新效劳条目URL
        .build();

    }
}

3.Spring MVC 相干设置

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    /**
     * 静态资本设置(默许)
     */
    @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);
    }


}

假如不增加此静态资本设置会报错,找不到相干途径

4.Model 中运用 Swagger 注解

@ApiModel(value = "UserEntity", description = "用户对象")
public class UserEntity implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 5237730257103305078L;
    @ApiModelProperty(value ="用户id",name="id",dataType="Long",required = false,example = "1",hidden = false )
    private Long id;
    @ApiModelProperty(value ="用户名",name="userName",dataType="String",required = false,example = "关羽" )
    private String userName;
    @ApiModelProperty(value ="用户性别",name="userSex",dataType="String",required = false,example = "男" )
    private String userSex;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

}

5. Controller 中运用 Swagger 注解


@RestController
@RequestMapping("/api")
@Api(tags = { "接口分组1", "接口分组2" })
public class ApiController {

    @Autowired
    private UserDao userDao;

    @GetMapping("/getAllUser")
    @ApiOperation(value = "猎取一切用户", notes = "", httpMethod = "GET", tags = "接口分组3")
    public List<UserEntity> getAll() {
        return userDao.getAll();
    }

    @GetMapping("/getUserById")
    @ApiOperation(value = "依据id猎取用户", notes = "id必传", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "用户id",example = "1", required = true, dataType = "long", paramType = "query")
    public UserEntity getOne(Long id) {
        return userDao.getOne(id);
    }

    @PostMapping("/getUserByNameAndSex")
    @ApiOperation(value = "依据name和sex猎取用户", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", example = "关羽", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userSex", value = "用户性别", example = "男", required = true, dataType = "string", paramType = "query") })
    public UserEntity getUserByNameAndSex(String userName, String userSex) {
        return userDao.getUserByNameAndSex(userName, userSex);
    }

    @PostMapping("/insertUser")
    @ApiOperation(value = "新增用户", notes = "传json,数据放body", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "body", value = "用户对象json", example = "{userName:'朝雾轻寒',userSex:'男'}", required = true) })
    public String insertUser(@RequestBody String body) {
        System.out.println(body);
        UserEntity user = JSON.parseObject(body, UserEntity.class);
        userDao.insertUser(user);
        return "{code:0,msg:'success'}";
    }

    @PostMapping("/updateUser")
    @ApiOperation(value = "修正用户", notes = "传json,数据放body", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "body", value = "用户对象json", example = "{id:23,userName:'朝雾轻寒',userSex:'女'}", required = true) })
    public String updateUser(@RequestBody String body) {
        System.out.println(body);
        UserEntity user = JSON.parseObject(body, UserEntity.class);
        userDao.updateUser(user);
        return "{code:0,msg:'success'}";
    }

    @PostMapping("/deleteUser")
    @ApiOperation(value = "删除用户", notes = "id必传", httpMethod = "POST")
    public String deleteUser(@ApiParam(name = "id", value = "用户id", required = true) Long id) {
        userDao.deleteUser(id);
        return "{code:0,msg:'success'}";
    }
}

5.测试

接见 http://127.0.0.1:8080/swagger-ui.html 举行接口在线测试

Swagger 经常使用注解

1.@Api

用于类,示意标识这个类是swagger的资本。属性以下:

  • tags 示意申明,tags假如有多个值,会生成多个列表
  • value 示意申明,能够运用tags替换

2.@ApiOperation

用于要领,示意一个http要求的操纵。属性以下:

  • value 用于要领形貌
  • notes 用于提醒内容
  • tags 用于API文档掌握的标记列表,视状况而用,能够举行自力分组

3.@ApiParam

用于要领、参数、字段申明;示意对参数的增加元数据。

  • name 参数名
  • value 参数申明
  • required 是不是必填

4.@ApiModel

用于类,示意对类举行申明,用于参数用实体类接收。

  • value 对象名
  • description 形貌

5.@ApiModelProperty

用于要领、字段,示意对model属性的申明或许数据操纵变动。

  • value 字段申明
  • name 重写属性名
  • dataType 重写属性数据范例
  • required 是不是必填
  • example 举例申明
  • hidden 隐蔽

6.@ApiIgnore

用于类、要领、要领参数,示意这个要领或许类被疏忽,不在swagger-ui.html上显现。

7.@ApiImplicitParam

用于要领,示意零丁的要求参数。

  • name 参数名
  • value 参数申明
  • dataType 数据范例
  • paramType 参数范例
  • example 举例申明

8.@ApiImplicitParams

用于要领,包括多个 @ApiImplicitParam。

9.@ApiResponses @ApiResponse

用于类或许要领,形貌操纵的能够响应。

  • code 响应的HTTP状况代码
  • message 响应附带的可读音讯

10.@ResponseHeader

用于要领,响应头设置。

  • name 响应头称号
  • description 头形貌
  • response 默许响应类 void
  • responseContainer 参考ApiOperation中设置

Swagger 导出离线 api 文档

1.导出 AsciiDocs、Markdown、Confluence 花样文档

增加依靠

<!-- swagger2markup 相干依靠 -->
        <dependency>
            <groupId>io.github.swagger2markup</groupId>
            <artifactId>swagger2markup</artifactId>
            <version>1.3.3</version>
        </dependency>

转换东西类

public class SwaggerUtils {

    private static final String url = "http://127.0.0.1:8080/v2/api-docs";
    /**
     * 生成AsciiDocs花样文档
     * @throws MalformedURLException
     */
    public static void generateAsciiDocs() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema().build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("./docs/asciidoc/generated"));
    }
    /**
     * 生成AsciiDocs花样文档,并汇总成一个文件
     * @throws MalformedURLException
     */
    public static void generateAsciiDocsToFile() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/asciidoc/generated/all"));
    }
    
    /**
     * 生成Markdown花样文档
     * @throws MalformedURLException
     */
    public static void generateMarkdownDocs() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("./docs/markdown/generated"));
    }
    /**
     * 生成Markdown花样文档,并汇总成一个文件
     * @throws MalformedURLException
     */
    public static void generateMarkdownDocsToFile() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.MARKDOWN)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/markdown/generated/all"));
    }
    
    /**
     * 生成Confluence花样文档
     * @throws MalformedURLException
     */
    public static void generateConfluenceDocs() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFolder(Paths.get("./docs/confluence/generated"));
    }
    
    /**
     * 生成Confluence花样文档,并汇总成一个文件
     * @throws MalformedURLException
     */
    public static void generateConfluenceDocsToFile() throws MalformedURLException {
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                .build();

        Swagger2MarkupConverter.from(new URL(url))
                .withConfig(config)
                .build()
                .toFile(Paths.get("./docs/confluence/generated/all"));
    }
    
    
}

运用测试 Controller

@RestController
@RequestMapping("/export")
@ApiIgnore
public class ExportController {

    
    @RequestMapping("/ascii")
    public String exportAscii() throws MalformedURLException{
        SwaggerUtils.generateAsciiDocs();
        return "success";
    }
    
    @RequestMapping("/asciiToFile")
    public String asciiToFile() throws MalformedURLException{
        SwaggerUtils.generateAsciiDocsToFile();
        return "success";
    }
    
    @RequestMapping("/markdown")
    public String exportMarkdown() throws MalformedURLException{
        SwaggerUtils.generateMarkdownDocs();
        return "success";
    }
    
    @RequestMapping("/markdownToFile")
    public String exportMarkdownToFile() throws MalformedURLException{
        SwaggerUtils.generateMarkdownDocsToFile();
        return "success";
    }
    
    @RequestMapping("/confluence")
    public String confluence() throws MalformedURLException{
        SwaggerUtils.generateConfluenceDocs();
        return "success";
    }
    
    @RequestMapping("/confluenceToFile")
    public String confluenceToFile() throws MalformedURLException{
        SwaggerUtils.generateConfluenceDocsToFile();
        return "success";
    }
}

2.导出 html、pdf、xml 花样

增加依靠

<!--离线文档 -->
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
        <!--springfox-staticdocs 生成静态文档 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-staticdocs</artifactId>
            <version>2.6.1</version>
        </dependency>
<build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>io.github.swagger2markup</groupId>
                    <artifactId>swagger2markup-maven-plugin</artifactId>
                    <version>1.3.1</version>
                    <configuration>
                        <swaggerInput>http://127.0.0.1:8080/v2/api-docs</swaggerInput>
                        <outputDir>./docs/asciidoc/generated</outputDir>
                        <config>
                            <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                        </config>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.asciidoctor</groupId>
                    <artifactId>asciidoctor-maven-plugin</artifactId>
                    <version>1.5.3</version>
                    <!-- <version>2.0.0-RC.1</version> -->
                    <!-- Include Asciidoctor PDF for pdf generation -->
                    <dependencies>
                        <dependency>
                            <groupId>org.asciidoctor</groupId>
                            <artifactId>asciidoctorj-pdf</artifactId>
                            <version>1.5.0-alpha.10.1</version>
                        </dependency>
                        <dependency>
                            <groupId>org.jruby</groupId>
                            <artifactId>jruby-complete</artifactId>
                            <version>1.7.21</version>
                        </dependency>
                    </dependencies>
                    <configuration>
                        <sourceDirectory>./docs/asciidoc/generated</sourceDirectory>
                        <outputDirectory>./docs/asciidoc/html</outputDirectory> 
                        <backend>html</backend>
                        <!-- <outputDirectory>./docs/asciidoc/pdf</outputDirectory> 
                        <backend>pdf</backend> -->
                        <headerFooter>true</headerFooter> 
                        <doctype>book</doctype> 
                        <sourceHighlighter>coderay</sourceHighlighter>
                        <attributes>
                            <!-- 菜单栏在左侧 -->
                            <toc>left</toc>
                            <!-- 多题目分列 -->
                            <toclevels>3</toclevels>
                            <!-- 自动打数字序号 -->
                            <sectnums>true</sectnums>
                        </attributes>
                    </configuration>                    
                </plugin>
            </plugins>
        </pluginManagement>

    </build>

能够修正此处 html 和 pdf,经由过程 mvn asciidoctor:process-asciidoc 能够导出响应花样文件

<outputDirectory>./docs/asciidoc/html</outputDirectory> 
                        <backend>html</backend>

实行 mvn asciidoctor:process-asciidoc 后再实行 mvn generate-resources,可在 targt/generated-docs 目次下生成 xml 花样文件。

完全代码

github

码云

  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  移步手机端
Spring Boot 2.X(十五):集成 Swagger2 开辟 API 文档(在线+离线)

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
未定义标签

本文来源:搜奇网

本文地址:https://www.sou7.cn/282367.html

关注我们:微信搜索“搜奇网”添加我为好友

版权声明: 本文仅代表作者个人观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。请记住本站网址https://www.sou7.cn/搜奇网。

发表评论

选填

必填

必填

选填

请拖动滑块解锁
>>