美文网首页
Springboot整合Swagger2

Springboot整合Swagger2

作者: 轻轻敲醒沉睡的心灵 | 来源:发表于2020-12-09 10:16 被阅读0次

    试用了swagger3,对springboot版本要求高不说,还是存在一些问题的,况且感觉swagger2用着还可以,就用swagger2吧!
    springboot整合swagger2三步曲:导包、配置、使用

    1. 导包

    <!--引入swagger -->
    <!-- 排除springfox-swagger2 引入的swagger-annotations、swagger-models 1.5.20版本,手动引入1.5.21版本的jar。
    因为在使用@ApiModelProperty注解在字段上时,如果字段的类型为Long或是int类型, 那么程序启动后,访问swagger-ui.html的页面,
    程序会报错: java.lang.NumberFormatException: For input string: "" -->
          <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
                <exclusions>
                    <exclusion>
                        <groupId>io.swagger</groupId>
                        <artifactId>swagger-annotations</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>io.swagger</groupId>
                        <artifactId>swagger-models</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger-ui</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-annotations</artifactId>
                <version>1.5.21</version>
            </dependency>
            <dependency>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-models</artifactId>
                <version>1.5.21</version>
            </dependency>
    

    2. 添加配置

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    //import org.springframework.context.annotation.Profile;
    
    import com.google.common.base.Function;
    import com.google.common.base.Optional;
    import com.google.common.base.Predicate;
    import com.google.common.base.Predicates;
    
    import cn.hutool.core.util.StrUtil;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import springfox.documentation.RequestHandler;
    import springfox.documentation.builders.ApiInfoBuilder;
    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 SwaggerConfig {
        
        // 定义分隔符,配置Swagger多包
        private static final String splitor = ";";
        
        @Bean
        public Docket api() {
            
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    // 指定扫描1个包
    //                .apis(RequestHandlerSelectors.basePackage("com.test.controller"))
                    // 扫描多包
                    .apis(scanBasePackage("com.test.controller"))
                    // 只有标记了@Api的类方法才会暴露出给swagger
                    .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                    // 只有标记了@ApiOperation的方法才会暴露出给swagger
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .build()
                    .apiInfo(apiInfo());
        }
        
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("接口文档")
    //                .description("Demo接口测试")
                    .version("1.0.0-SNAPSHOT")
    //                .termsOfServiceUrl("")
                    .build();
        }
        
        
        
        /**
         * 方法1:重写basePackage方法,使能够实现多包访问
         */
         public static Predicate<RequestHandler> basePackage(final String basePackage) {
             return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
         }
    
         private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
             return input -> {
                 // 循环判断匹配
                 for (String strPackage : basePackage.split(splitor)) {
                     boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                     if (isMatch) {
                         return true;
                     }
                 }
                 return false;
             };
         }
    
         @SuppressWarnings("deprecation")
        private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
             return Optional.fromNullable(input.declaringClass());
         }
         
         /**
          * 方法2:切割扫描的包生成Predicate<RequestHandler>
          */
        public static Predicate<RequestHandler> scanBasePackage(final String basePackage) {
            if(StrUtil.isBlank(basePackage)){
                throw new NullPointerException("basePackage不能为空,多个包扫描使用" + splitor + "分隔");
            }
            String[] controllerPack = basePackage.split(splitor);
            Predicate<RequestHandler> predicate = null;
            for (int i = controllerPack.length -1; i >= 0 ; i--) {
                String strBasePackage = controllerPack[i];
                if (StrUtil.isNotBlank(strBasePackage)) {
                    Predicate<RequestHandler> tempPredicate = RequestHandlerSelectors.basePackage(strBasePackage);
                    predicate = predicate == null ? tempPredicate : Predicates.or(tempPredicate,predicate);
                }
            }
            if(predicate == null) {
                throw new NullPointerException("basePackage配置不正确,多个包扫描使用" + splitor + "分隔");
            }
            return predicate;
        }
    }
    

    3. 使用

    swagger2使用

    相关文章

      网友评论

          本文标题:Springboot整合Swagger2

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