美文网首页
使用Swagger自动生成文档

使用Swagger自动生成文档

作者: 莫夏_b560 | 来源:发表于2019-06-18 21:04 被阅读0次

    1、Swagger使用
    第一步: 导入依赖

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

    第二步: 开启@EnableSwagger2注解

    @SpringBootApplication
    @RestController
    @EnableSwagger2
    public class DemoApplication {
    

    第三步:访问http://localhost:8080/swagger-ui.html

    image.png

    备注:由于在使用时,误导入了springmvc的jar包。swagger-ui.html请求一直报错

    2、自定义路径

    package com.abel.example;
    
    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 Swagger2 {
        /**
         * 创建API应用
         * apiInfo() 增加API相关信息
         * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
         * 本例采用指定扫描的包路径来定义指定要建立API的目录。
         *
         * @return
         */
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.abel.example.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        /**
         * 创建该API的基本信息(这些基本信息会展现在文档页面中)
         * 访问地址:http://项目实际地址/swagger-ui.html
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Spring Boot中使用Swagger2构建RESTful APIs")
                    .description("更多请关注https://blog.csdn.net/u012373815")
                    .termsOfServiceUrl("https://blog.csdn.net/u012373815")
                    .contact("abel")
                    .version("1.0")
                    .build();
        }
    }
    

    相关文章

      网友评论

          本文标题:使用Swagger自动生成文档

          本文链接:https://www.haomeiwen.com/subject/qkgqqctx.html